Showing posts with label Testing. Show all posts
Showing posts with label Testing. Show all posts

Thursday, June 16, 2011

Exploratory Testing: Did a Parameter Object Get Changed?

Exploratory testing is a useful way to find out how legacy code works. If you can write tests that exercise the legacy code in all its paths, you can then feel much safer in refactoring the code. If the refactored code still passes the tests, the refactoring is correct and has not created any side effects.

Sometimes parameter objects are modified inside methods. One way to test for this is to create two instances, pass one in to the method, and then compare the one passed in to see if it is equal to the unmodified one. This assumes that you have a correct implementation of equals().


public class LegacyTest {
private Legacy legacy;
private PassedIn passedIn;
private PassedIn untouched;


@Before
public void setUp()
throws Exception {
legacy = new Legacy();
passedIn = new PassedIn();
untouched = new PassedIn();
}

@Test
public void passedInDidNotChange() {
assertEquals(untouched, passedIn);
legacy.method(passedIn);
assertEquals(untouched, passedIn);
}
}

Friday, May 20, 2011

Refactoring Code with Static Dependencies for Testability

Methods that have dependencies on static methods can be difficult to test. In this example we have a dependency that we obtain via a static method that we do not have control over and we want to test the surrounding code.

public void myMethod(Long id) {
// ...
Dependency dependency = DependencyUtil.getDependency();
// ...
}

We can refactor this to:

public void myMethod(Long id) {
Dependency dependency = DependencyUtil.getDependency();
myMethod(dependency);
}

void myMethod(Long id, Dependency dependency) {
// ...
doSomething(dependency);
// ...
}

We overload the method signature and preserve the public API. We make the new method have default access to make it testable. We can now mock Dependency however we like.