测试类中的构造函数不能被可用的注射剂所满足

时间:2016-05-27 19:33:57

标签: java junit mocking jmockit

我正在使用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

我似乎没有初始化需要测试的类的实例以及需要模拟的类。

1 个答案:

答案 0 :(得分:2)

可注射的模拟旨在传递给被测代码。 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.
}