mauron85
mauron85

Reputation: 1544

Mockito mocking callback interface

I have very basic service with method post that updates it's progress via callback interface.

public class HttpPostService {
    public interface UploadingProgressListener {
        void onProgress(int progress);
    }

    public int post(InputStream body, UploadingProgressListener listener)
    {
         // shortened for brevity
         // read inputstream and writes bytes to HttpURLConnection outputstream
         // read inputstream in loop notify listener about progress
         listener.onProgress(percentage);
    }
}

I would like to test this class with Mockito, basically mock UploadingProgressListener and then check if it was called n-times with correct percentage arguments.

@Test
public void testPostFileProgressListener() throws IOException {
    UploadingProgressListener mockListener = mock(UploadingProgressListener.class);

    InputStream inputStream = new ByteArrayInputStream();
    service.postFile(inputStream, mockListener);
    verify(mockListener, times(5)).onProgress(100);
}

However when I run test it says it was only invoked one time, but when I debug it listener was called 5 times.

I know there is concept of Answers and ArgumentCaptors, but I thought at least counting how many times mock was called would be correct. Thanks for any help.

Upvotes: 0

Views: 201

Answers (1)

JB Nizet
JB Nizet

Reputation: 691685

If you indeed want to check that there was an ordered sequence of 5 calls, with 20, 40, 60, 80 and 100 as argument, you just need

    InOrder inOrder = inOrder(mockListener);
    inOrder.verify(mockListener).onProgress(20);
    inOrder.verify(mockListener).onProgress(40);
    inOrder.verify(mockListener).onProgress(60);
    inOrder.verify(mockListener).onProgress(80);
    inOrder.verify(mockListener).onProgress(100);

If you just want to check that the listener has been called 5 times, without caring about the arguments, then just use

    verify(mockListener, times(5)).onProgress(anyInt());

Upvotes: 1

Related Questions