Reputation: 122
I have a class in which I would like to verify method calls
Here is a representation of my class :
public class MyClass {
public void method1(String id) {
MyClass inst = this.getParticularInstance(id);
if(inst != null) {
inst.doSomething();
}
}
public MyClass getParticularInstance(String id) {
// return a particular object or null
}
public void doSomething(String id) {
// do something
}
}
In particular, I would like to make sure that when I call method1, getParticularInstance is called, and depending of the result, doSomething is called or not.
Is it possible to test such a code with Mockito, and if yes is it the right way ?
Thank you
Upvotes: 2
Views: 1131
Reputation: 4857
Spy the MyClass and use verify()
to verify the method invocation
@RunWith(MockitoJUnitRunner.class)
public class MyClassTest {
private MyClass myClass;
@Before
public void setUp() {
myClass = spy(new MyClass());
}
public void testMethod1() {
// Arrange
String id = "id1";
// Act
myClass.method1(id);
// Assert
verify(myClass).getParticularInstance(id);
}
}
Upvotes: 2