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