Slipping a Fake
Slipping Technique: Extract and Override
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 extract it to a new method and override in tests to get a hard coded data instead.
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
}
}
(Reading...)
Formatting Hints:
To format... | use this markup: |
---|---|
source code | {source:lang=java|lineNumbers=false}...{source} (Supported languages: java, cpp, csharp, c, python.) |
bold text | __some text__ |
italicized text | ~~some text~~ |
underlined text | @@some text@@ |
a method or class name | ``myMethod(...)`` |