[英]How to partially mock a dependency abstract object in JMockit
I have abstract class D
which is a dependency of the tested class T
. 我有抽象类
D
,它是经过测试的类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. 我希望
dependency.doSomething()
将运行此方法的实际代码,但是抽象方法将被模拟。
If I run the test as is, I obviously get NullPointerException
for using the uninitialized dependency
. 如果按原样运行测试,则显然会因为使用未初始化的
dependency
收到NullPointerException
。
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. 如果我添加
@Mocked
注释到D dependency
线,在所有的方法D
被嘲笑,所以d.doSomething()
不会做它应该做的。
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: 如果我保留
@Mocked
批注并在测试方法的开头添加一个空的NonStrictExpectations
块,则可以进行部分模拟,如下所示:
new NonStrictExpectations(D.class) {};
or like this: 或像这样:
new NonStrictExpectations(d) {};
I get java.lang.IllegalArgumentException: Already mocked: class D
. 我得到
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
. 如果我保留
NonStrictExpectations
块并删除@Mocked
批注,则再次会因使用未初始化的dependency
得到NullPointerException
。
So how can I partially mock this dependency abstract class? 那么,如何部分模拟该依赖抽象类呢?
Using the @Capturing
annotation on the dependency achieves this. 在依赖项上使用
@Capturing
批注可实现此目的。 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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.