已测试 class 中没有构造函数可以通过可用的注射器满足

No constructor in tested class that can be satisfied by available injectables

我正在使用 JMockit 模拟依赖 class 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

看来我没有初始化需要测试和模拟的 class 的实例。

可注入模拟旨在传递到被测代码中。 ClassToBeTested 代码不允许通过构造函数或方法传入依赖项的实例。相反,您应该只用 @Mocked 注释 NeedToBeMockedClass ,然后在期望块中指定行为。 @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.
}