网络单元测试:如何测试作为传递的ChannelHandlerContext一部分的Channel对象的调用?

问题描述 投票:0回答:1

ChannelHandler实现的部分行为是,它应该在收到消息后发送响应。但是,传递的ChannelHandlerContext似乎确实创建了一个内部Channel实例,该实例与单元测试中使用的EmbeddedChannel实例不同。因此,不可能从外部测试响应是否实际上已写入通道。

这里有一些代码可以澄清问题:

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
}
java unit-testing netty
1个回答
0
投票

尽可能简单:

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));
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.