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

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

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
}

越简单越好:

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