Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test a function with a callback?

Tags:

java

junit

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?

like image 318
manabreak Avatar asked Aug 17 '15 12:08

manabreak


People also ask

What is a callback in a function?

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.

Can a callback function call another function?

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.

Is callback the same as 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.


1 Answers

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();
like image 163
David Avatar answered Oct 27 '22 01:10

David