How to unit test netty handler

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

I searched for "netty unit test" and found one article that talked about CodecEmbedder, but I still don't know where to start. Do you have any example or tips on how to unit test Netty code?

Thank you very much.

+6
source share
1 answer

Netty has various ways to check the network stack.

ChannelHandlers Testing

You can use the Netty EmbeddedChannel to make fun of a network 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); } 

This test is above tests for StringDecoder's ability to decode unicode correctly ( example from this error sent by me )

You can also check the encoding direction with the EmbeddedChannel , for this you have to use writeOutBound and readInbound .

Additional examples:

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(); } 

Additional examples on github.

Bytebuf

To check if you are bytebuf s, you can set a JVM parameter that checks for ByteBuf leak, for this you need to add -Dio.netty.leakDetectionLevel=PARANOID to the startup parameters or call the ResourceLeakDetector.setLevel(PARANOID) method.

+6
source

Source: https://habr.com/ru/post/955748/


All Articles