netty实战笔记 第九章 单元测试

客官°小女子只卖身不卖艺 2022-04-04 10:28 311阅读 0赞

9.1 EmbeddedChannel 概述

netty提供了Embedded传输,用于测试ChannelHandler. 这个服传输是一种特殊的Channel实现,EmbeddedChannel的功能,这个实现提供了通过ChannelPipeline传播事件的简便方法。

具体的思路是:将入站数据或者出站数据写到EmbeddedChannel中,然后检查是否有任何东西到达了ChannelPipeline的尾端。这样便可以确定消息是否已经被Handler处理。

下面是EmbeddedChannel的API






























方法名称 作用
writeInbound(Object… msgs) 将入站消息写到EmbeddedChannel 中。如果可以通过readInbound()方法从EmbeddedChannel 中读取数据,则返回true
readInbound() 从EmbeddedChannel 中读取一个入站消息。任何返回的东西都穿越了整个ChannelPipeline。如果没有任何可供读取的,则返回null
writeOutbound(Object… msgs) 将出站消息写到EmbeddedChannel中。如果现在可以通过readOutbound()方法从EmbeddedChannel 中读取到什么东西,则返回true
readOutbound() 从EmbeddedChannel 中读取一个出站消息。任何返回的东西都穿越了整个ChannelPipeline。如果没有任何可供读取的,则返回null
finish() 将EmbeddedChannel 标记为完成,并且如果有可被读取的入站数据或者出站数据,则返回true。这个方法还将会调用EmbeddedChannel

入站数据由ChannelInboundHandler 处理,代表从远程节点读取的数据。出站数据由ChannelOutboundHandler 处理,代表将要写到远程节点的数据。

看下EmbeddedChannel的数据流图
在这里插入图片描述

在每种情况下,消息都将会传递过ChannelPipeline,并且被相关的ChannelInboundHandler 或者hannelOutboundHandler 处理。如果消息没有被消费,那么你可以使用readInbound()或者readOutbound()方法来在处理过了这些消息之后,酌情把它们从Channel中读出来。

9.2 使用EmbeddedChannel测试ChannelHandler

9.2.1 测试入站消息

使用Demo:

  1. package com.moyang3.testInbound;
  2. import io.netty.buffer.ByteBuf;
  3. import io.netty.channel.ChannelHandlerContext;
  4. import io.netty.handler.codec.ByteToMessageDecoder;
  5. import java.util.List;
  6. public class FixedLengthFrameDecoder extends ByteToMessageDecoder {
  7. private final int frameLength;
  8. public FixedLengthFrameDecoder (int frameLength) {
  9. if(frameLength < 0) {
  10. throw new IllegalArgumentException("!!!!");
  11. }
  12. this.frameLength = frameLength;
  13. }
  14. protected void decode (ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
  15. while(byteBuf.readableBytes() >= frameLength) {
  16. ByteBuf buf = byteBuf.readBytes(frameLength);
  17. list.add(buf);
  18. }
  19. }
  20. }
  21. package com.moyang3.testInbound;
  22. import io.netty.buffer.ByteBuf;
  23. import io.netty.buffer.Unpooled;
  24. import io.netty.channel.embedded.EmbeddedChannel;
  25. import io.netty.handler.codec.FixedLengthFrameDecoder;
  26. public class FixedLengthFrameDecoderTest {
  27. public void testFramesDecoded () {
  28. ByteBuf buf = Unpooled.buffer();
  29. for(int i = 0; i < 9; i++) {
  30. buf.writeByte(i);
  31. }
  32. ByteBuf input = buf.duplicate();
  33. EmbeddedChannel channel = new EmbeddedChannel(new FixedLengthFrameDecoder(3));
  34. assert channel.writeInbound(input.retain());
  35. assert(channel.finish());
  36. }
  37. }

9.2.3 测试出站消息

略。

最后

如果你觉得写的还不错,就关注下公众号呗,关注后,有点小礼物回赠给你。
你可以获得5000+电子书,java,springCloud,adroid,python等各种视频教程,IT类经典书籍,各种软件的安装及破解教程。
希望一块学习,一块进步!
在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,311人围观)

还没有评论,来说两句吧...

相关阅读