怎麼對ChannelHandler作測試?

使用EmbeddedChannel。它的數據流程以下所示:bash

  • writeOutbound:將出站消息寫到EmbeddedChannel中,若是能經過readOutbound從EmbeddedChannel中讀到數據,返回true
  • readOutbound:從EmbeddedChannel中讀取一個出站消息,它所返回的全部東西都會穿過整個的ChannelPipeline。若是沒有讀取的,就返回null
  • writeInbound:將入站消息寫到EmbeddedChannel中,若是能經過readInbound從EmbeddedChannel中讀取數據,返回true
  • readInbound:從EmbeddedChannel中讀取一個入站消息,任何返回都會通過ChannelPipeline。若是沒有讀取,返回null

測試案例

ByteBuf buf=Upooled.buffer();
for(int i=1;i<10;i++){
	buf.writeInt(i*-1);
}
//MyAbsChannelHandler 負責將每一個負數轉爲正數,並一個一個的輸出
EmbeddedChannel channel=new EmbeddedChannel(new MyAbsChannelHandler());
assertTrue(channel.writeOutbound(buf));
//finish 表示將 EmbeddedChannel 標記爲完成,若是有可讀的入站數據或出站數據,返回true
assertTrue(channel.finish());

for(int i=1;i<10;i++){
	assertEquals(i,channel.readOutbound());
}
assertNull(channel.readOutbound())
複製代碼
相關文章
相關標籤/搜索