我实现了一个扩展 SimpleChannelHandler 的处理程序,并覆盖了一些方法,例如 channelConnected、messageReceived。但是,我想知道如何对其进行单元测试?
我搜索了“netty 单元测试”并找到了 one article其中说考虑 CodecEmbedder,但我仍然不确定如何开始。你有任何关于如何对 Netty 代码进行单元测试的例子或建议吗?
非常感谢。
最佳答案
在 Netty 中,有多种方法可以测试您的网络堆栈。
测试 ChannelHandler
您可以使用 Netty 的 EmbeddedChannel
模拟一个用于测试的网络连接,一个例子是:
@Test
public void nettyTest() {
EmbeddedChannel channel = new EmbeddedChannel(new StringDecoder(StandardCharsets.UTF_8));
channel.writeInbound(Unpooled.wrappedBuffer(new byte[]{(byte)0xE2,(byte)0x98,(byte)0xA2}));
String myObject = channel.readInbound();
// Perform checks on your object
assertEquals("☢", myObject);
}
上面的这个测试测试 StringDecoder 解码 unicode 正确性的能力 ( example from this bug posted by me )
您还可以使用
EmbeddedChannel
测试编码器方向,为此你应该使用 writeOutBound
和 readInbound
.更多示例:
DelimiterBasedFrameDecoderTest.java :
@Test
public void testIncompleteLinesStrippedDelimiters() {
EmbeddedChannel ch = new EmbeddedChannel(new DelimiterBasedFrameDecoder(8192, true,
Delimiters.lineDelimiter()));
ch.writeInbound(Unpooled.copiedBuffer("Test", Charset.defaultCharset()));
assertNull(ch.readInbound());
ch.writeInbound(Unpooled.copiedBuffer("Line\r\ng\r\n", Charset.defaultCharset()));
assertEquals("TestLine", releaseLater((ByteBuf) ch.readInbound()).toString(Charset.defaultCharset()));
assertEquals("g", releaseLater((ByteBuf) ch.readInbound()).toString(Charset.defaultCharset()));
assertNull(ch.readInbound());
ch.finish();
}
More examples on github.
字节缓冲区
测试您是否使用您的
bytebuf
s,你可以设置一个JVM参数来检查泄漏的ByteBuf,为此,你应该添加-Dio.netty.leakDetectionLevel=PARANOID
到启动参数,或调用方法ResourceLeakDetector.setLevel(PARANOID)
.
关于unit-testing - 如何对 netty 处理程序进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19312306/