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

相关文章
|
24天前
|
Java 关系型数据库 数据库连接
Mybatis+MySQL动态分页查询数据经典案例(含代码以及测试)
Mybatis+MySQL动态分页查询数据经典案例(含代码以及测试)
24 1
|
2月前
|
测试技术
包含用例执行时间的测试报告代码
包含用例执行时间的测试报告代码
|
4月前
com串口通信测试代码
com串口通信测试代码
26 0
|
4月前
|
存储 人工智能 C#
【Unity 3D】C#中数组、集合、栈、队列、哈希表、字典的讲解(附测试代码)
【Unity 3D】C#中数组、集合、栈、队列、哈希表、字典的讲解(附测试代码)
36 0
|
4月前
|
监控 前端开发 JavaScript
如何测试前端代码? 知道 BDD, TDD, Unit Test 么? 知道怎么测试你的前端工程么(mocha, sinon, jasmin, qUnit..)?
如何测试前端代码? 知道 BDD, TDD, Unit Test 么? 知道怎么测试你的前端工程么(mocha, sinon, jasmin, qUnit..)?
74 0
|
1月前
|
Java 测试技术
单元测试编写可测试代码
单元测试编写可测试代码
19 2
|
2月前
|
存储 测试技术
统计测试结果的代码实现接昨天
统计测试结果的代码实现接昨天
|
3月前
|
Dubbo Java 应用服务中间件
【分布式技术专题】「探索高性能远程通信」基于Netty的分布式通信框架实现(附通信协议和代码)(上)
今天,我要向大家实现一个基于Netty实现的高性能远程通信框架!这个框架利用了 Netty 的强大功能,提供了快速、可靠的远程通信能力。 无论是构建大规模微服务架构还是实现分布式计算,这个分布式通信框架都是一个不可或缺的利器。
60 2
【分布式技术专题】「探索高性能远程通信」基于Netty的分布式通信框架实现(附通信协议和代码)(上)
|
3月前
|
网络协议 Linux C语言
C语言-多播测试代码(IPv4和IPv6)
C语言-多播测试代码(IPv4和IPv6)
35 0
|
3月前
|
前端开发 网络协议 Java
Netty | 工作流程图分析 & 核心组件说明 & 代码案例实践
Netty | 工作流程图分析 & 核心组件说明 & 代码案例实践
106 0