I want to check the specific order in which characters to ensure that they are not distorted. I tried to write it using InOrder, but it does not seem to work, or at least in Mockito 1.8.5.
InOrder
@Test 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 ); inOrder.verifyNoMoreInteractions(); }
Test failed with message:
Verification in order failure: mockWriter.write(108); Wanted 1 time: -> at org.bitbucket.artbugorski.brainfuj.interpreter.InterpreterTest.inOrderTest(InterpreterTest.java:62) But was 3 times. Undesired invocation: -> at org.bitbucket.artbugorski.brainfuj.interpreter.InterpreterTest.inOrderTest(InterpreterTest.java:58)
How to write a Mockito test for this?
EDIT: Filed as bug http://code.google.com/p/mockito/issues/detail?id=296
; , , , , - . Mockito stubbing , Mockito , . ; , - , , .
ArgumentCaptor . , "Hello world". , , .
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()); }
, .
- , - , , 'l' Mockito, , , , , 'l " , () . , Mockito, , , , , , . , , , Writer. , . StringWriter .
assertThat(stringWriter.toString(), equalTo(message));
, , , , Mockito, , , , , , .
, Mockito, - . , , API -:) , api.
... . -, ( ) . , ! =)
, , ... . David ArgumentCaptor .
, !
.
final List<Integer> writtenChars = new ArrayList<>(); willAnswer( new Answer(){ @Override public Object answer( final InvocationOnMock invocation )throws Throwable { final int arg = (int) invocation.getArguments()[0]; writtenChars.add( arg ); return null; } } ).given( mockWriter ).write( anyInt() );
final Iterator<Integer> writtenCharItr = writtenChars.iterator(); for( int charInt : "Hello World!\n".toCharArray() ) assertThat( charInt, is( writtenCharItr.next() ) ); assertThat( "There are no more chars.", writtenCharItr.hasNext(), is(false) ); verify( mockWriter ).flush();
, , , ..
: , , , , , , StringBuilder List, ,
StringBuilder
List
, API. , Mockito, API- .
Unitils Mock:
Mock<Writer> mockWriter; @Test public void inOrderTest() throws Exception { Writer writer = mockWriter.getMock(); final String message = "Hello World!\n"; for (char c : message.toCharArray()) writer.write(c); for (char c : message.toUpperCase().toCharArray()) mockWriter.assertInvokedInSequence().write(c); MockUnitils.assertNoMoreInvocations(); }
JMockit ( ):
@Test public void inOrderTest(final Writer mockWriter) throws Exception { final String message = "Hello World!\n"; for (char c : message.toCharArray()) mockWriter.write(c); new FullVerificationsInOrder() {{ for (char c : message.toCharArray()) mockWriter.write(c); }}; }