在 Netty 中,有多种方法可以测试您的网络堆栈。
测试 ChannelHandlers
您可以使用 Netty 的 EmbeddedChannel 模拟 netty 连接进行测试,例如:
@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.
字节缓冲区
要测试你是否使用bytebufs,你可以设置一个JVM参数来检查泄漏的ByteBuf,为此你应该在启动参数中添加-Dio.netty.leakDetectionLevel=PARANOID,或者调用方法ResourceLeakDetector.setLevel(PARANOID)。