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

相关文章
|
1天前
|
SQL JavaScript 前端开发
基于Python访问Hive的pytest测试代码实现
根据《用Java、Python来开发Hive应用》一文,建立了使用Python、来开发Hive应用的方法,产生的代码如下
12 6
基于Python访问Hive的pytest测试代码实现
|
3天前
|
测试技术 UED
软件测试的艺术:从代码到品质的探索之旅
在数字时代的浪潮中,软件已成为我们生活和工作不可或缺的一部分。然而,高质量的软件背后隐藏着一门鲜为人知的艺术——软件测试。本文将带你走进这门艺术的世界,从基础理论到实践应用,一起探索如何通过软件测试保障产品质量,提升用户体验,并最终实现从代码到品质的华丽转变。
|
1天前
|
SQL JavaScript 前端开发
基于Java访问Hive的JUnit5测试代码实现
根据《用Java、Python来开发Hive应用》一文,建立了使用Java、来开发Hive应用的方法,产生的代码如下
15 6
|
2天前
|
测试技术 持续交付
软件测试的艺术:从代码到信心的旅程
探索软件测试不仅仅是发现错误的技术过程,它是一场从编码到用户信心的转化之旅。本文将带你了解如何通过创造性思维和系统方法,将软件测试变成一门艺术,确保产品质量的同时,提升用户对技术的信赖。
18 3
|
23天前
|
JSON Dubbo 测试技术
单元测试问题之增加JCode5插件生成的测试代码的可信度如何解决
单元测试问题之增加JCode5插件生成的测试代码的可信度如何解决
42 2
单元测试问题之增加JCode5插件生成的测试代码的可信度如何解决
|
6天前
|
人工智能 计算机视觉
AI计算机视觉笔记十五:编写检测的yolov5测试代码
该文为原创文章,如需转载,请注明出处。本文作者在成功运行 `detect.py` 后,因代码难以理解而编写了一个简易测试程序,用于加载YOLOv5模型并检测图像中的对象,特别是“人”类目标。代码实现了从摄像头或图片读取帧、进行颜色转换,并利用YOLOv5进行推理,最后将检测框和置信度绘制在输出图像上,并保存为 `result.jpg`。如果缺少某些模块,可使用 `pip install` 安装。如涉及版权问题或需获取完整代码,请联系作者。
|
10天前
|
敏捷开发 安全 测试技术
软件测试的艺术:从代码到信心的旅程
在数字时代的浪潮中,软件成为我们日常生活和工作不可或缺的一部分。然而,高质量的软件背后隐藏着一群默默无闻的英雄——软件测试工程师。本文将带你一探究竟,软件测试不仅仅是找出错误的技术活动,它更是一门确保产品质量、提升用户信心的艺术。我们将从测试的重要性出发,探索不同的测试类型,深入理解测试用例的设计,并讨论如何通过持续集成和自动化测试来提高效率。无论你是软件开发者还是对软件质量感兴趣的读者,这篇文章都将为你提供新的视角和深入的洞见。
|
16天前
|
人工智能 API Python
Openai python调用gpt测试代码
这篇文章提供了使用OpenAI的Python库调用GPT-4模型进行聊天的测试代码示例,包括如何设置API密钥、发送消息并接收AI回复。
|
14天前
|
测试技术 C# 开发者
“代码守护者:详解WPF开发中的单元测试策略与实践——从选择测试框架到编写模拟对象,全方位保障你的应用程序质量”
【8月更文挑战第31天】单元测试是确保软件质量的关键实践,尤其在复杂的WPF应用中更为重要。通过为每个小模块编写独立测试用例,可以验证代码的功能正确性并在早期发现错误。本文将介绍如何在WPF项目中引入单元测试,并通过具体示例演示其实施过程。首先选择合适的测试框架如NUnit或xUnit.net,并利用Moq模拟框架隔离外部依赖。接着,通过一个简单的WPF应用程序示例,展示如何模拟`IUserRepository`接口并验证`MainViewModel`加载用户数据的正确性。这有助于确保代码质量和未来的重构与扩展。
25 0
|
14天前
|
数据库 测试技术 开发者
Play Framework的测试魔法:让代码在舞台上翩翩起舞,确保应用质量的幕后英雄!
【8月更文挑战第31天】Play Framework不仅以其高效开发与部署流程著称,还内置了强大的测试工具,提供全面的测试支持,确保应用高质量和稳定性。本文将详细介绍如何在Play Framework中进行单元测试和集成测试,涵盖`WithApplication`、`WithServer`及`WithDatabase`等类的使用方法,并通过示例代码手把手教你如何利用Play的测试框架。无论是单元测试、集成测试还是数据库操作测试,Play Framework均能轻松应对,助你提升应用质量和开发效率。
19 0