Album Cover

Faking & Mocking Java

Close Preview
If the method under test uses an awkward collaborator to get data,
extract it to a new method and override in tests to get a hard coded data instead.
The method interestingFunction() of Interesting uses an AwkwardCollaborator to get a boolean value.
What if we don't really care to test the collaborator, but want test coverage for both paths through our code?

public class Interesting…
	public void interestingFunction() {
		…
		if(collaborator.checkSomething()) {
			//do something
		}
		else {
			//do something else
		}
	}

public class Interesting…
	public void interestingFunction() {
		…
		if(extractedCheckSomething()) {
			//do something
		}
		else {
			//do something else
		}
	}
protected boolean extractedCheckSomething() { return collaborator.checkSomething(); }

public class InterestingTest…
	@Test
	public void interestingHappyPath() {
		Interesting interesting = new Interesting() {
			protected boolean extractedCheckSomething() {
				return true;
			}
		};
		interesting.interestingFunction();
		//assert that something happened
	}
@Test public void interestingSadPath() { Interesting interesting = new Interesting() { protected boolean extractedCheckSomething() { return false; } }; interesting.interestingFunction(); //assert that something else happened }
Read more about the Extract & Override technique in our Legacy Code album.
(Reading...)
| Tweet...
Page rating: | Rate this Page