Java – exception: mockito wants but is not called, but actually interacts with zero of this simulation
•
Java
I have an interface
Interface MyInterface { myMethodToBeVerified (String,String); }
The implementation interface is
class MyClassToBeTested implements MyInterface { myMethodToBeVerified(String,String) { ……. } }
I have another class
class MyClass { MyInterface myObj = new MyClassToBeTested(); public void abc(){ myObj.myMethodToBeVerified (new String(“a”),new String(“b”)); }
}
I'm writing JUnit for MyClass I've done it
class MyClassTest { MyClass myClass = new MyClass(); @Mock MyInterface myInterface; testAbc(){ myClass.abc(); verify(myInterface).myMethodToBeVerified(new String(“a”),new String(“b”)); } }
But I got what mockito wanted, but it was not called. In fact, the interaction with the simulation was zero when verifying the call
Someone can propose some solutions
Solution
You need to inject simulation into the class you test You are currently interacting with real objects, not simulated objects You can fix the code in the following ways:
void testAbc(){ myClass.myObj = myInteface; myClass.abc(); verify(myInterface).myMethodToBeVerified(new String(“a”),new String(“b”)); }
Although extracting all the initialization code into @ before would be a wiser choice
@Before void setUp(){ myClass = new myClass(); myClass.myObj = myInteface; } @Test void testAbc(){ myClass.abc(); verify(myInterface).myMethodToBeVerified(new String(“a”),new String(“b”)); }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码