Netty In Action中文版 - 第十章:单元测试代码

Netty In Action中文版 - 第十章:单元测试代码

本章介绍

  • 单元测试
  • EmbeddedChannel

学会了使用一个或多个ChannelHandler处理接收/发送数据消息,但是如何测试它们呢?Netty提供了2个额外的类使得测试ChannelHandler变得很容易,本章讲解如何测试Netty程序。测试使用JUnit4,如果不会用可以慢慢了解。JUnit4很简单,但是功能很强大。本章将重点讲解测试已实现的ChannelHandler和编解码器。

10.1 General

        正如前面所学的,Netty提供了一个简单的方法在ChannelPipeline上“堆叠”不同的ChannelHandler实现。所有的ChannelHandler都会参与处理事件,这个设计允许独立出可重用的小逻辑块,它只处理一个任务。这不仅使代码更清晰,也更容易测试。
        测试ChannelHandler可以通过使用“嵌入式”传输很容易的传递事件槽管道以测试你的实现。对于这个嵌入式传输,Netty提供了一个特定的Channel实现:EmbeddedChannel。但是它是如何工作的呢?EmbeddedChannel的工作非常简单,它允许写入入站或出站数据,然后检查ChannelPipeline的结束。这允许你检查消息编码/解码或触发ChannelHandler任何行为。
        编写入站和出站的却别是什么?入站数据是通过ChannelInboundHandler处理,代表从远程对等通道读取数据;出站数据是通过ChannelOutboundHandler处理,代表写入数据到远程对等通道。因此测试ChannelHandler就会选择writeInbound(...)或writeOutbound()(或者都选择)。
        EmbeddedChannel提供了下面一些方法:
  • writeInbound(Object...),写一个消息到入站通道
  • writeOutbound(Object...),写消息到出站通道
  • readInbound(),从EmbeddedChannel读取入站消息,可能返回null
  • readOutbound(),从EmbeddedChannel读取出站消息,可能返回null
  • finish(),标示EmbeddedChannel已结束,任何写数据都会失败

为了更清楚的了解其处理过程,看下图:

        如上图所示,使用writeOutbound(...)写消息到通道,消息在出站方法通过ChannelPipeline,之后就可以使用readOutbound()读取消息。着同样使用与入站,使用writeInbound(...)和readInbound()。处理入站和出站是相似的,它总是遍历整个ChannelPipeline直到ChannelPipeline结束,并将处理过的消息存储在EmbeddedChannel中。下面来看看如何测试你的逻辑。

10.2 测试ChannelHandler

        测试ChannelHandler最好的选择是使用EmbeddedChannel。

10.2.1 测试处理入站消息的handler

        我们来编写一个简单的ByteToMessageDecoder实现,有足够的数据可以读取时将产生固定大小的包,如果没有足够的数据可以读取,则会等待下一个数据块并再次检查是否可以产生一个完整包。下图显示了重新组装接收的字节:
        如上图所示,它可能会占用一个以上的“event”以获取足够的字节产生一个数据包,并将它传递到ChannelPipeline中的下一个ChannelHandler,看下面代码:

[java] view plain copy

  1. package netty.in.action;
  2. import java.util.List;
  3. import io.netty.buffer.ByteBuf;
  4. import io.netty.channel.ChannelHandlerContext;
  5. import io.netty.handler.codec.ByteToMessageDecoder;
  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.                     "frameLength must be a positive integer: " + frameLength);
  12.         }
  13.         this.frameLength = frameLength;
  14.     }
  15.     @Override
  16.     protected void decode(ChannelHandlerContext ctx, ByteBuf in,
  17.             List<Object> out) throws Exception {
  18.         while (in.readableBytes() >= frameLength) {
  19.             ByteBuf buf = in.readBytes(frameLength);
  20.             out.add(buf);
  21.         }
  22.     }
  23. }

解码器的实现完成了,写一个单元测试的方法是个好主意。即使代码看起来没啥问题,但是也应该进行单元测试,这样能在部署到生产之前就发现问题。现在让我们来看看如何使用EmbeddedChannel来完成测试,看下面代码:

[java] view plain copy

  1. package netty.in.action;
  2. import io.netty.buffer.ByteBuf;
  3. import io.netty.buffer.Unpooled;
  4. import io.netty.channel.embedded.EmbeddedChannel;
  5. import org.junit.Assert;
  6. import org.junit.Test;
  7. public class FixedLengthFrameDecoderTest {
  8.     @Test
  9.     public void testFramesDecoded() {
  10.         ByteBuf buf = Unpooled.buffer();
  11.         for (int i = 0; i < 9; i++) {
  12.             buf.writeByte(i);
  13.         }
  14.         ByteBuf input = buf.duplicate();
  15.         EmbeddedChannel channel = new EmbeddedChannel(
  16.                 new FixedLengthFrameDecoder(3));
  17.         // write bytes
  18.         Assert.assertTrue(channel.writeInbound(input));
  19.         Assert.assertTrue(channel.finish());
  20.         // read message
  21.         Assert.assertEquals(buf.readBytes(3), channel.readInbound());
  22.         Assert.assertEquals(buf.readBytes(3), channel.readInbound());
  23.         Assert.assertEquals(buf.readBytes(3), channel.readInbound());
  24.         Assert.assertNull(channel.readInbound());
  25.     }
  26.     @Test
  27.     public void testFramesDecoded2() {
  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(
  34.                 new FixedLengthFrameDecoder(3));
  35.         Assert.assertFalse(channel.writeInbound(input.readBytes(2)));
  36.         Assert.assertTrue(channel.writeInbound(input.readBytes(7)));
  37.         Assert.assertTrue(channel.finish());
  38.         Assert.assertEquals(buf.readBytes(3), channel.readInbound());
  39.         Assert.assertEquals(buf.readBytes(3), channel.readInbound());
  40.         Assert.assertEquals(buf.readBytes(3), channel.readInbound());
  41.         Assert.assertNull(channel.readInbound());
  42.     }
  43. }

如上面代码,testFramesDecoded()方法想测试一个ByteBuf,这个ByteBuf包含9个可读字节,被解码成包含了3个可读字节的ByteBuf。你可能注意到,它写入9字节到通道是通过调用writeInbound()方法,之后再执行finish()来将EmbeddedChannel标记为已完成,最后调用readInbound()方法来获取EmbeddedChannel中的数据,直到没有可读字节。testFramesDecoded2()方法采取同样的方式,但有一个区别就是入站ByteBuf分两步写的,当调用writeInbound(input.readBytes(2))后返回false时,FixedLengthFrameDecoder值会产生输出,至少有3个字节是可读,testFramesDecoded2()测试的工作相当于testFramesDecoded()。

10.2.2 测试处理出站消息的handler

        测试处理出站消息和测试处理入站消息不太一样,例如有一个继承MessageToMessageEncoder的AbsIntegerEncoder类,它所做的事情如下:
  • 将已接收的数据flush()后将从ByteBuf读取所有整数并调用Math.abs(...)
  • 完成后将字节写入ChannelPipeline中下一个ChannelHandler的ByteBuf中

看下图处理过程:

看下面代码:

[java] view plain copy

  1. package netty.in.action;
  2. import java.util.List;
  3. import io.netty.buffer.ByteBuf;
  4. import io.netty.channel.ChannelHandlerContext;
  5. import io.netty.handler.codec.MessageToMessageEncoder;
  6. public class AbsIntegerEncoder extends MessageToMessageEncoder<ByteBuf> {
  7.     @Override
  8.     protected void encode(ChannelHandlerContext ctx, ByteBuf msg,
  9.             List<Object> out) throws Exception {
  10.         while(msg.readableBytes() >= 4){
  11.             int value = Math.abs(msg.readInt());
  12.             out.add(value);
  13.         }
  14.     }
  15. }

下面代码是测试AbsIntegerEncoder:

[java] view plain copy

  1. package netty.in.action;
  2. import io.netty.buffer.ByteBuf;
  3. import io.netty.buffer.Unpooled;
  4. import io.netty.channel.embedded.EmbeddedChannel;
  5. import org.junit.Assert;
  6. import org.junit.Test;
  7. public class AbsIntegerEncoderTest {
  8.     @Test
  9.     public void testEncoded() {
  10.         //创建一个能容纳10个int的ByteBuf
  11.         ByteBuf buf = Unpooled.buffer();
  12.         for (int i = 1; i < 10; i++) {
  13.             buf.writeInt(i * -1);
  14.         }
  15.         //创建EmbeddedChannel对象
  16.         EmbeddedChannel channel = new EmbeddedChannel(new AbsIntegerEncoder());
  17.         //将buf数据写入出站EmbeddedChannel
  18.         Assert.assertTrue(channel.writeOutbound(buf));
  19.         //标示EmbeddedChannel完成
  20.         Assert.assertTrue(channel.finish());
  21.         //读取出站数据
  22.         ByteBuf output = (ByteBuf) channel.readOutbound();
  23.         for (int i = 1; i < 10; i++) {
  24.             Assert.assertEquals(i, output.readInt());
  25.         }
  26.         Assert.assertFalse(output.isReadable());
  27.         Assert.assertNull(channel.readOutbound());
  28.     }
  29. }

10.3 测试异常处理

有时候传输的入站或出站数据不够,通常这种情况也需要处理,例如抛出一个异常。这可能是你错误的输入或处理大的资源或其他的异常导致。我们来写一个实现,如果输入字节超出限制长度就抛出TooLongFrameException,这样的功能一般用来防止资源耗尽。看下图:

        上图显示帧的大小被限制为3字节,若输入的字节超过3字节,则超过的字节被丢弃并抛出TooLongFrameException。在ChannelPipeline中的其他ChannelHandler实现可以处理TooLongFrameException或者忽略异常。处理异常在ChannelHandler.exceptionCaught()方法中完成,ChannelHandler提供了一些具体的实现,看下面代码:

[java] view plain copy

  1. package netty.in.action;
  2. import java.util.List;
  3. import io.netty.buffer.ByteBuf;
  4. import io.netty.channel.ChannelHandlerContext;
  5. import io.netty.handler.codec.ByteToMessageDecoder;
  6. import io.netty.handler.codec.TooLongFrameException;
  7. public class FrameChunkDecoder extends ByteToMessageDecoder {
  8.     // 限制大小
  9.     private final int maxFrameSize;
  10.     public FrameChunkDecoder(int maxFrameSize) {
  11.         this.maxFrameSize = maxFrameSize;
  12.     }
  13.     @Override
  14.     protected void decode(ChannelHandlerContext ctx, ByteBuf in,
  15.             List<Object> out) throws Exception {
  16.         // 获取可读字节数
  17.         int readableBytes = in.readableBytes();
  18.         // 若可读字节数大于限制值,清空字节并抛出异常
  19.         if (readableBytes > maxFrameSize) {
  20.             in.clear();
  21.             throw new TooLongFrameException();
  22.         }
  23.         // 读取ByteBuf并放到List中
  24.         ByteBuf buf = in.readBytes(readableBytes);
  25.         out.add(buf);
  26.     }
  27. }

测试FrameChunkDecoder的代码如下:

[java] view plain copy

  1. package netty.in.action;
  2. import io.netty.buffer.ByteBuf;
  3. import io.netty.buffer.Unpooled;
  4. import io.netty.channel.embedded.EmbeddedChannel;
  5. import io.netty.handler.codec.TooLongFrameException;
  6. import org.junit.Assert;
  7. import org.junit.Test;
  8. public class FrameChunkDecoderTest {
  9.     @Test
  10.     public void testFramesDecoded() {
  11.         //创建ByteBuf并填充9字节数据
  12.         ByteBuf buf = Unpooled.buffer();
  13.         for (int i = 0; i < 9; i++) {
  14.             buf.writeByte(i);
  15.         }
  16.         //复制一个ByteBuf
  17.         ByteBuf input = buf.duplicate();
  18.         //创建EmbeddedChannel
  19.         EmbeddedChannel channel = new EmbeddedChannel(new FrameChunkDecoder(3));
  20.         //读取2个字节写入入站通道
  21.         Assert.assertTrue(channel.writeInbound(input.readBytes(2)));
  22.         try {
  23.             //读取4个字节写入入站通道
  24.             channel.writeInbound(input.readBytes(4));
  25.             Assert.fail();
  26.         } catch (TooLongFrameException e) {
  27.         }
  28.         //读取3个字节写入入站通道
  29.         Assert.assertTrue(channel.writeInbound(input.readBytes(3)));
  30.         //标识完成
  31.         Assert.assertTrue(channel.finish());
  32.         //从EmbeddedChannel入去入站数据
  33.         Assert.assertEquals(buf.readBytes(2), channel.readInbound());
  34.         Assert.assertEquals(buf.skipBytes(4).readBytes(3),
  35.                 channel.readInbound());
  36.     }
  37. }

10.4 Summary

In this chapter you learned how you are be able to test your custom ChannelHandler and so make  sure  it works  like  you  expected. Using  the  shown  techniques  you  are  now  be  able  to make use of JUnit and so ultimately test your code as your are used to. Using the techniques shown in the chapter you will be able to guarantee a high quality of your code and also guard it from misbehavior..  In the next chapters we will focus on writing "real" applications on top of Netty and so show you  how  you  can make  real  use  of  it.  Even  if  the  applications  don't  contain  any  test-code remember it is quite important to do so when you will write your next-gen application.

原文地址http://www.bieryun.com/2178.html

优秀的个人博客,低调大师

微信关注我们

原文链接:https://yq.aliyun.com/articles/539966

转载内容版权归作者及来源网站所有!

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

相关文章

发表评论

资源下载

更多资源
优质分享Android(本站安卓app)

优质分享Android(本站安卓app)

近一个月的开发和优化,本站点的第一个app全新上线。该app采用极致压缩,本体才4.36MB。系统里面做了大量数据访问、缓存优化。方便用户在手机上查看文章。后续会推出HarmonyOS的适配版本。

Mario,低调大师唯一一个Java游戏作品

Mario,低调大师唯一一个Java游戏作品

马里奥是站在游戏界顶峰的超人气多面角色。马里奥靠吃蘑菇成长,特征是大鼻子、头戴帽子、身穿背带裤,还留着胡子。与他的双胞胎兄弟路易基一起,长年担任任天堂的招牌角色。

Eclipse(集成开发环境)

Eclipse(集成开发环境)

Eclipse 是一个开放源代码的、基于Java的可扩展开发平台。就其本身而言,它只是一个框架和一组服务,用于通过插件组件构建开发环境。幸运的是,Eclipse 附带了一个标准的插件集,包括Java开发工具(Java Development Kit,JDK)。

Sublime Text 一个代码编辑器

Sublime Text 一个代码编辑器

Sublime Text具有漂亮的用户界面和强大的功能,例如代码缩略图,Python的插件,代码段等。还可自定义键绑定,菜单和工具栏。Sublime Text 的主要功能包括:拼写检查,书签,完整的 Python API , Goto 功能,即时项目切换,多选择,多窗口等等。Sublime Text 是一个跨平台的编辑器,同时支持Windows、Linux、Mac OS X等操作系统。