In this article we will use thenAnswer method of Mockito to invoke a callback method passed to a mock.
Let's consider following classes.
Here, ServiceToBeTested class is calling submitCallback() method of ServiceToBeMocked class and passing it a Callback object.
The value set in Callback object is latter returned by the method being tested.
ServiceToBeTested.java
public class ServiceToBeTested {
private final ServiceToBeMocked serviceToBeMocked;
public ServiceToBeTested(ServiceToBeMocked serviceToBeMocked) {
this.serviceToBeMocked = serviceToBeMocked;
}
public String methodToBeTested() {
Callback callback = new Callback();
serviceToBeMocked.submitCallback(callback);
return "Value Received after callback = " + callback.getValue();
}
}
ServiceToBeMocked.java
public class ServiceToBeMocked {
public void submitCallback(Callback callback) {
//some logic that sets value back in callback.
callback.setValue(null);
}
}
Callback.java
/**
* Simple class demonstrating callback events. The implementation could be much more complex.
*/
public class Callback {
private String value;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
In above scenario, thenReturn method of Mockito will be of no use. We can use thenAnswer() method in this case to achieve our test scenario.
ServiceToBeTestedTest.java
@ExtendWith(MockitoExtension.class)
class ServiceToBeTestedTest {
@Mock
private ServiceToBeMocked serviceToBeMocked;
@InjectMocks
private ServiceToBeTested serviceToBeTested;
@Test
void test_callback() {
Mockito.doAnswer(it -> {
Callback callback = it.getArgument(0);
callback.setValue("Mocked Value");
return null;
}).when(serviceToBeMocked).submitCallback(Mockito.any(Callback.class));
String returnValue = serviceToBeTested.methodToBeTested();
Assertions.assertEquals("Value Received after callback = Mocked Value", returnValue);
}
}
Full sample code can be found at our Github repository.
0 comments:
Post a Comment