我正在使用 JMockit 来模拟依赖类 NeedToBeMockedClass
public class ClassToBeTested{
private NeedToBeMockedClass needToBeMockedObj;
public ClassToBeTested(String a, boolean b){
needToBeMockedObj = new NeedToBeMockedClass(String x, int y);
}
public String helloWorld(String m, String n){
// do smething
needToBeMockedObj.someMethod(100, 200);
// do smething more
}
}
测试用例
@Tested
private ClassToBeTested classUnderTest;
@Injectable
NeedToBeMockedClass mockInstance;
@Test
public void testHelloWorld(){
new NonStrictExpectations(classUnderTest) {
{
Deencapsulation.invoke(mockInstance, "someMethod", withAny(AnotherClassInstance.class), 200);
result = true;
}
};
//verification
}
我遇到了异常
java.lang.IllegalArgumentException: No constructor in tested class that can be satisfied by available injectables
看来我没有初始化需要测试和需要模拟的类的实例。
最佳答案
可注入(inject)的模拟旨在传递到被测试的代码中。 ClassToBeTested 代码不允许通过构造函数或方法传入依赖项的实例。相反,您应该只使用 @Mocked 注释 NeedToBeMockedClass,然后在期望 block 中指定行为。 @Mocked 注释模拟在测试代码中执行的 NeedToBeMockedClass 的任何实例。
@Test
public void testHelloWorld(@Mocked final NeedToBeMockedClass mockInstance){
new NonStrictExpectations() {
{
mockInstance.someMethod(anyInt, anyInt);
result = true;
}
};
ClassToBeTested classToBeTested = new ClassToBeTested("", true);
String result = classToBeTested.helloWorld("", "");
//Assertions, verifications, etc.
}
关于java - 测试类中没有可以由可用注入(inject)满足的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37491039/