如何对Netty处理程序进行单元测试 [英] How to unit test netty handler

查看:237
本文介绍了如何对Netty处理程序进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实现了一个扩展SimpleChannelHandler的处理程序,并覆盖了一些方法,例如channelConnected,messageReceived.但是,我想知道如何对其进行单元测试?

I implement a handler which extends SimpleChannelHandler, and overrides some methods such as channelConnected, messageReceived. However, I am wondering how to unit test it?

我搜索了"netty单元测试",发现一篇文章其中说考虑使用CodecEmbedder,但是我仍然不确定如何开始.关于如何对Netty代码进行单元测试,您有任何示例或建议吗?

I searched about "netty unit test" and found one article which said considering CodecEmbedder, but I am still not sure how to begin. Do you have any example or advice on how to unit test Netty code?

非常感谢.

推荐答案

在Netty中,有多种测试网络堆栈的方法.

In Netty, there are different ways to test your networking stack.

您可以使用Netty的EmbeddedChannel来模拟netty连接进行测试,例如:

You can use Netty's EmbeddedChannel to mock a netty connection for testing, an example of this would be:

@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的能力(我发布的此错误的示例)

This test above tests for StringDecoder ability to decode unicode correct (example from this bug posted by me)

您还可以使用EmbeddedChannel测试编码器方向,为此,您应该使用writeOutBoundreadInbound.

You can also test the encoder direction using EmbeddedChannel, for this you should use writeOutBound and 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上的更多示例.

要测试是否使用bytebuf,可以设置一个JVM参数来检查泄漏的ByteBuf,为此,应在启动参数中添加-Dio.netty.leakDetectionLevel=PARANOID或调用方法ResourceLeakDetector.setLevel(PARANOID).

To test if you use your bytebufs, you can set a JVM parameter that checks for leaked ByteBuf, for this, you should add -Dio.netty.leakDetectionLevel=PARANOID to the startup parameters, or call the method ResourceLeakDetector.setLevel(PARANOID).

这篇关于如何对Netty处理程序进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆