I have abstract class D
which is a dependency of the tested class T
.
The test class:
public class T_Test {
@Tested T tested;
D dependency;
public void test() {
dependency.doSomething();
tested.testedMethod(dependency);
}
}
I want the dependency.doSomething()
will run the real code of this method, but that the abstract methods will be mocked.
If I run the test as is, I obviously get
NullPointerException
for using the uninitializeddependency
.If I add the
@Mocked
annotation to theD dependency
line, all the methods inD
are mocked, sod.doSomething()
doesn't do what it's supposed to do.If I keep the
@Mocked
annotation and also add an emptyNonStrictExpectations
block at the beginning of the test method, in order to have partial mock, either like this:new NonStrictExpectations(D.class) {};
or like this:
new NonStrictExpectations(d) {};
I get
java.lang.IllegalArgumentException: Already mocked: class D
.If I keep the
NonStrictExpectations
block and remove the@Mocked
annotation, again I getNullPointerException
for using the uninitializeddependency
.
So how can I partially mock this dependency abstract class?
Using the
@Capturing
annotation on the dependency achieves this. No need to add an empty expectations block; only the abstract methods will be mocked.