I am using JMockit to mock the dependent 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
}
}
Test Case
@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
}
I'm getting below exception
java.lang.IllegalArgumentException: No constructor in tested class that can be satisfied by available injectables
It appears I'm not initializing instance of the class which need to be tested and the which need to be mocked.
Injectable mocks are intended to be passed into the code under test. The ClassToBeTested code does not allow for an instance of the dependency to be passed in via constructor or method. Instead you should just annotate NeedToBeMockedClass with @Mocked and then specify behavior in an expectation block. The @Mocked annotation mocks any instance of the NeedToBeMockedClass executed in the code under test.
@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.
}