Home » Java » java – Netty unit testing: How to test invocations on the Channel object that is part of the passed ChannelHandlerContext?-Exceptionshub

java – Netty unit testing: How to test invocations on the Channel object that is part of the passed ChannelHandlerContext?-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

Part of the behavior of a ChannelHandler implementation is that it should send a response after receiving a message. However, the passed ChannelHandlerContext does seem to create an internal Channel instance that is not equal to the EmbeddedChannel instance used in the unit test. So, it is not possible to test from outside that a response has actually been written to the channel.

Here is some code to clarify the problem:

public class EchoHandler extends SimpleChannelInboundHandler<Object>
{
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception
    {
        ctx.channel().writeAndFlush(msg);
    }
}

@Test
public void aTest() throws Exception
{
    EchoHandler handler = new EchoHandler();
    EmbeddedChannel channel = spy(new EmbeddedChannel(handler));
    Object anObject = new Object();
    channel.writeInbound(anObject);
    verify(channel, times(1)).writeAndFlush(eq(anObject)); // will fail
}
How to&Answers:

As simple as it gets:

public class EchoHandlerTest {

    static class EchoHandler extends ChannelInboundHandlerAdapter {

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            ctx.channel().writeAndFlush(msg);
        }
    }

    @Test
    public void aTest() throws Exception {
        EmbeddedChannel channel = new EmbeddedChannel(new EchoHandler());
        Object anObject = new Object();
        channel.writeInbound(anObject);
        assertThat(channel.readOutbound(), is(anObject));
    }
}