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 uninitialized dependency
.
If I add the @Mocked
annotation to the D dependency
line, all the methods in D
are mocked, so d.doSomething()
doesn't do what it's supposed to do.
If I keep the @Mocked
annotation and also add an empty NonStrictExpectations
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 get NullPointerException
for using the uninitialized dependency
.
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.
public class T_Test {
@Tested T tested;
@Capturing D dependency;
public void test() {
dependency.doSomething();
tested.testedMethod(dependency);
}
}