Sebi
Sebi

Reputation: 184

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

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
}

Upvotes: 1

Views: 1002

Answers (1)

forty-two
forty-two

Reputation: 12817

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

Upvotes: 2

Related Questions