javaandroidunit-testingmocking

Unit test a callback


I am trying to write unit tests for a Presenter in my application and I have the following use case, for which I don't know how I should go about writing a Unit test.

interface ICallback
{
    void onConfirm(String str);
}

interface IPopup
{
    void show(ICallback callback);
}

class Presenter
{
    private IPopup m_popup;
    private String m_result;

    Presenter(IPopup popup)
    {
        m_popup = popup;
    }

    public String getResult() { return m_result; }

    void onClick()
    {
        m_popup.show(new ICallback()
        {
            @Override
            public void onConfirm(String str)
            {
                m_result = str;
            }
        });
    }
}

The function show creates a PopupWindow that has an OK button whose onClick method calls ICallback.onConfirm.

I would like to test what happens inside onConfirm(), but I have no idea how to go about it. How does one do this? Or should I structure my code differently so it will more test friendly?


Solution

  • Found a solution

    I used ArgumentCaptor to capture the callback and then called the onConfirm method of the callback and verified if it did it's job.

    @Mock IPopup m_popup;
    
    @Test
    public void callbackTest()
    {
        String str = "test";
        ArgumentCaptor<ICallback> argument = ArgumentCaptor.forClass(ICallback.class);
    
        m_presenter.onClick();
        verify(m_popup).show(argument.capture());
    
        argument.getValue().onConfirm(str);
        assertEquals(str, m_presenter.getResult());
    }