Netty では、ネットワーク スタックをテストするさまざまな方法があります。
ChannelHandler のテスト
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);
}
上記のこのテストは、Unicode を正しくデコードする StringDecoder の能力をテストします (私が投稿したこのバグの例)
を使用してエンコーダの方向をテストすることもでき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();
}
github のその他の例。
バイトバッファ
sを使用しているかどうかをテストするにbytebuf
は、リークされた ByteBuf をチェックする JVM パラメータを設定できます。これには-Dio.netty.leakDetectionLevel=PARANOID
、起動パラメータに追加するか、メソッドを呼び出す必要がありますResourceLeakDetector.setLevel(PARANOID)
。