咱们在前面的章节中知道,ChannelHandler在ChannelPipeline中是有多个连接起来的,当咱们只想对某个ChannelHandler进行测试的时候,咱们能够用特殊的Channel实现——EmbeddedChannel来达到咱们测试的目的。
主要的方法以下:segmentfault
// 将入站消息写入到EmbeddedChannel中 public boolean writeInbound(Object... msgs) // 从EmbeddedChannel中读取入站消息 public <T> T readInbound() // 将出站消息写入到EmbeddedChannel中 public boolean writeInbound(Object... msgs) // 从EmbeddedChannel中读取出站消息 public <T> T readOutbound() // 将EmbeddedChannel标记为已完成 public boolean finish()
EmbeddedChannel的数据流测试
FirstHandler和SecondHandler的代码见以前的代码spa
public static void main(String[] args) { testInbound(); testOutbound(); } public static void testOutbound() { System.out.println("----------------testOutbound----------------"); ByteBuf buf = Unpooled.buffer(); buf.writeBytes("hello".getBytes()); EmbeddedChannel channel = new EmbeddedChannel( new SecondHandler()); channel.writeOutbound(buf); ByteBuf o =channel.readOutbound(); System.out.println(o.toString(CharsetUtil.UTF_8)); } public static void testInbound() { System.out.println("----------------testInbound----------------"); ByteBuf buf = Unpooled.buffer(); buf.writeBytes("hello".getBytes()); EmbeddedChannel channel = new EmbeddedChannel( new FirstHandler()); channel.writeInbound(buf); ByteBuf o = channel.readInbound(); System.out.println(o.toString(CharsetUtil.UTF_8)); }
运行结果以下:code