lambda(编年史队)的Mockito CommentCaptor



我已经在编年史中实现了,为此,我想编写单元测试用例。在使用lambda时,如何捕获参数captor参数。我想在测试案例中获取WriteBuffer来验证数据。

public class Persister  {
public Persister(SingleChronicleQueue chronicle) {
    this.chronicle = chronicle;
}
public void write(int outBufferOffset) throws IOException {
       ExcerptAppender appender = chronicle.acquireAppender();
       appender.writeBytes(b -> {
               b.writeInt(outBufferOffset);                    
               b.write(writeBuffer, 0 , outBufferOffset);
       });}
}

测试案例:

@Mock
SingleChronicleQueue chronicle;
@Mock
ExcerptAppender appender;
@Captor
ArgumentCaptor<WriteBytesMarshallable> argumentCaptorLambda;
Persister persister = new Persister();
@Test
public void shouldPersistByteMessage() throws IOException {
    persister.write(MESSAGEBYTES);
    verify(appender).writeBytes(argumentCaptorLambda.capture());
    WriteBytesMarshallable lastValue =  argumentCaptorLambda.getValue();
    //final byte[] persistedBytes = ?? how to get writeBuffer here ??
    //assertThat(readPersistedMessage(persistedBytes), is(MESSAGE));
}

谢谢

我已将Doanswer用于此实现

@Captor
ArgumentCaptor<WriteBytesMarshallable> argumentCaptorLambda;
@Mock private BytesOut bytesOut;

public void shouldPersistReliableMessage() throws IOException {
        doAnswer(invocationOnMock -> {
            WriteBytesMarshallable marshallable = (WriteBytesMarshallable) invocationOnMock.getArguments()[0];
            marshallable.writeMarshallable(bytesOut);
            return null;
        }).when(appender).writeBytes((WriteBytesMarshallable)any());
        persister.persist(MESSAGEBYTES);
        verify(bytesOut).writeInt(84);
        verify(bytesOut).write(argumentCaptor.capture(), eq(0), eq(84));
        assertThat(readPersistedMessage(argumentCaptor.getValue()), is(MESSAGE));
    }

相关内容

  • 没有找到相关文章

最新更新