Since the datastructure of my application domain is becoming pretty complex as of late, I started reading up on mock objects. Soon a simple question came to my mind, but the answer has proven to be quite the headache so far. So here goes:
We have a class 'Foo' with 'bar' as one of its methods:
class Foo {
public String bar(int i){
if(i == 1) return "arrr!";
}
}
And we have a class Pirate calling Foo.bar(1); in one of its methods:
class Pirate {
public String yell(){
Foo foo = new Foo();
return foo.bar(1);
}
Now we mock the Foo class in the unit test of the Pirate class because Foo happens to have a plethora of other dependencies:
@Test
public void returnsPirateString() {
Pirate blackBeard = new Pirate();
Foo fooMock = mock(Foo.class);
fooMock.expectAndReturn("bar",1,"arrr!"); //expects 'bar' function to be called once and returns "arrr!"
assertEquals(blackBeard.yell(),"arrr!");
}
What happens now, is that if we refactor method bar to return null instead of "arrr!", our test will keep running happily while our program does not work the way we want it to. This may result in a possible debugging nightmare.
Using a mockist approach instead of the classical testing approach to unit testing, most of the time all "helper" objects get mocked, and only the tested object remains unmocked, so the previously stated problem can occur quite often as well.
What can be done to prevent this problem while mocking?