Suppose we have an interface for a callback function as such:
public interface Callback
{
void foo();
}
And we have a method that calls a callback that was given as an argument:
public void doSomething(final Callback callback)
{
// Do something, like asynchronously fetch something from a server
asyncStuff.doSomethingAsync(new AsyncResponseHandler()
{
@Override
public void asyncStuffDone()
{
// Call the callback
callback.foo();
}
});
}
Now, to the question: Given this kind of scenario, how would one test that the callback indeed gets called?
A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.
Yes. The print( ) function takes another function as a parameter and calls it inside. This is valid in JavaScript and we call it a “callback”. So a function that is passed to another function as a parameter is a callback function.
The callback is a function that's accepted as an argument and executed by another function (the higher-order function). There are 2 kinds of callback functions: synchronous and asynchronous. The synchronous callbacks are executed at the same time as the higher-order function that uses the callback.
Supply a mock Callback
object for the test and validate that the method was invoked. For example, using Mockito as a mocking library, you would create a mock object (arrange):
Callback myMock = mock(Callback.class);
Then supply it to the code being tested (act):
someObject.doSomething(myMock);
And validate that the method was invoked (assert):
verify(myMock, times(1)).foo();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With