我是netty framework的新手。我们有一个API Handler实现SimpleChannelInboundHandler并覆盖ChannelRead0函数,它接受ChannelHandlerContext和FullHTTPRequest.Now我需要进行单元测试模拟输入。 任何人都可以帮助我。
答案 0 :(得分:0)
让我们假设我想测试我的MyContentExtractionHandler
,如下所示:
public class MyContentExtractionHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
int contentLenght = msg.content().capacity();
byte[] content = new byte[contentLenght];
msg.content().getBytes(0, content);
ctx.fireChannelRead(new String(content));
}
}
我将创建常规DefaultFullHttpRequest
并使用mockito来模拟ChannelHandlerContext
。我的单元测试看起来像这样:
public class MyContentExtractionHandlerTest {
@Mock
ChannelHandlerContext mockCtx = BDDMockito.mock(ChannelHandlerContext.class);
MyContentExtractionHandler myContentExtractorHandler = new MyContentExtractionHandler();
@Test
public void myTest() throws Exception {
String content = "MyContentHello";
DefaultFullHttpRequest fullHttpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/my /uri", Unpooled.copiedBuffer(content.getBytes()));
myContentExtractorHandler.channelRead(mockCtx, fullHttpRequest);
BDDMockito.verify(mockCtx).fireChannelRead(content); //verify that fireChannelRead was called once with the expected result
}
}
最有可能的是,您的SimpleChannelInboundHandler
将成为最终的处理程序。因此,在阅读消息后,不要检查fireChannelRead()
检查您调用的任何方法。