How to test ChannelHandler?

How to test ChannelHandler?

Use EmbeddedChannel. Its data flow is as follows:

  • writeOutbound: Write the outbound message to the EmbeddedChannel, if the data can be read from the EmbeddedChannel through readOutbound, return true
  • readOutbound: Read an outbound message from EmbeddedChannel, and everything it returns will pass through the entire ChannelPipeline. If there is no read, it returns null
  • writeInbound: Write the inbound message to the EmbeddedChannel, if the data can be read from the EmbeddedChannel through readInbound, return true
  • readInbound: Read an inbound message from EmbeddedChannel, and any return will go through ChannelPipeline. If there is no read, return null

Test Case

ByteBuf buf=Upooled.buffer();
for(int i=1;i<10;i++){
	buf.writeInt(i*-1);
}
//MyAbsChannelHandler  
EmbeddedChannel channel=new EmbeddedChannel(new MyAbsChannelHandler());
assertTrue(channel.writeOutbound(buf));
//finish   EmbeddedChannel  , true
assertTrue(channel.finish());

for(int i=1;i<10;i++){
	assertEquals(i,channel.readOutbound());
}
assertNull(channel.readOutbound())