How to test in Mockito for a specific order of calls with the same arguments?


I want to verify the specific order in which characters to ensure that they aren't getting garbled. I tried writing it using InOrder but it seems not to work, or at least in Mockito 1.8.5.

public void inOrderTest() throws IOException{
    final String message = "Hello World!\n";

    for( char c : message.toCharArray() )
        mockWriter.write( c );

    final InOrder inOrder = inOrder( mockWriter );
    for( char c : message.toCharArray() )
        inOrder.verify( mockWriter ).write( c );

The test above fails with the message:

Verification in order failure:
Wanted 1 time:
-> at     org.bitbucket.artbugorski.brainfuj.interpreter.InterpreterTest.inOrderTest(
But was 3 times. Undesired invocation:
-> at org.bitbucket.artbugorski.brainfuj.interpreter.InterpreterTest.inOrderTest(

How does one write a Mockito test for that?

EDIT: Filed as bug

My apologies to the previous respondents; but in my opinion, using an Answer flies a little in the face of one of the basic ideas of Mockito, namely that stubbing and verifying are two completely separate processes. Mockito has features for stubbing and features for verification, and the makers of Mockito have made an effort to keep the two separate. Answers are intended for stubbing; and whereas there are a few cases where an Answer is the best way to verify, I don't believe this is one of them.

I would use an ArgumentCaptor instead of an Answer. I would write a method like this in the test class, then call it with "Hello world" as the argument. Note that I haven't tested this, so it may contain typos.

private void verifyCharactersWritten( String expected ){
    ArgumentCaptor<Character> captor = ArgumentCaptor.forClass( Character.class );
    verify( mockWriter, times( expected.length())).write( captor.capture());
    assertEquals( Arrays.asList( expected.toCharArray()), captor.getAllValues());

Hope this helps.