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

相关文章
|
数据采集 机器学习/深度学习 大数据
行为检测代码(一):超详细介绍C3D架构训练+测试步骤
这篇文章详细介绍了C3D架构在行为检测领域的应用,包括训练和测试步骤,使用UCF101数据集进行演示。
833 1
行为检测代码(一):超详细介绍C3D架构训练+测试步骤
|
11月前
|
测试技术 开发者 Python
Python单元测试入门:3个核心断言方法,帮你快速定位代码bug
本文介绍Python单元测试基础,详解`unittest`框架中的三大核心断言方法:`assertEqual`验证值相等,`assertTrue`和`assertFalse`判断条件真假。通过实例演示其用法,帮助开发者自动化检测代码逻辑,提升测试效率与可靠性。
640 1
|
算法 IDE Java
Java 项目实战之实际代码实现与测试调试全过程详解
本文详细讲解了Java项目的实战开发流程,涵盖项目创建、代码实现(如计算器与汉诺塔问题)、单元测试(使用JUnit)及调试技巧(如断点调试与异常排查),帮助开发者掌握从编码到测试调试的完整技能,提升Java开发实战能力。
996 0
|
10月前
|
安全 Java 测试技术
《深入理解Spring》单元测试——高质量代码的守护神
Spring测试框架提供全面的单元与集成测试支持,通过`@SpringBootTest`、`@WebMvcTest`等注解实现分层测试,结合Mockito、Testcontainers和Jacoco,保障代码质量,提升开发效率与系统稳定性。
|
机器学习/深度学习 人工智能 监控
提升软件质量的关键路径:高效测试策略与实践在软件开发的宇宙中,每一行代码都如同星辰般璀璨,而将这些星辰编织成星系的过程,则依赖于严谨而高效的测试策略。本文将引领读者探索软件测试的奥秘,揭示如何通过精心设计的测试方案,不仅提升软件的性能与稳定性,还能加速产品上市的步伐,最终实现质量与效率的双重飞跃。
在软件工程的浩瀚星海中,测试不仅是发现缺陷的放大镜,更是保障软件质量的坚固防线。本文旨在探讨一种高效且创新的软件测试策略框架,它融合了传统方法的精髓与现代技术的突破,旨在为软件开发团队提供一套系统化、可执行性强的测试指引。我们将从测试规划的起点出发,沿着测试设计、执行、反馈再到持续优化的轨迹,逐步展开论述。每一步都强调实用性与前瞻性相结合,确保测试活动能够紧跟软件开发的步伐,及时适应变化,有效应对各种挑战。
|
11月前
|
人工智能 边缘计算 搜索推荐
AI产品测试学习路径全解析:从业务场景到代码实践
本文深入解析AI测试的核心技能与学习路径,涵盖业务理解、模型指标计算与性能测试三大阶段,助力掌握分类、推荐系统、计算机视觉等多场景测试方法,提升AI产品质量保障能力。
|
测试技术 Go 开发者
如何为 gRPC Server 编写本地测试代码
本文介绍了如何使用 Go 语言中的 gRPC 测试工具 **bufconn**,通过内存连接实现 gRPC Server 的本地测试,避免端口冲突和外部依赖。结合示例代码,讲解了初始化内存监听、自定义拨号器及编写测试用例的完整流程,并借助断言库提升测试可读性与准确性。适用于单元及集成测试,助力高效开发。
303 1
|
安全 Java 测试技术
Java 项目实战中现代技术栈下代码实现与测试调试的完整流程
本文介绍基于Java 17和Spring技术栈的现代化项目开发实践。项目采用Gradle构建工具,实现模块化DDD分层架构,结合Spring WebFlux开发响应式API,并应用Record、Sealed Class等新特性。测试策略涵盖JUnit单元测试和Testcontainers集成测试,通过JFR和OpenTelemetry实现性能监控。部署阶段采用Docker容器化和Kubernetes编排,同时展示异步处理和反应式编程的性能优化。整套方案体现了现代Java开发的最佳实践,包括代码实现、测试调试
404 0
|
人工智能 自然语言处理 测试技术
自然语言生成代码一键搞定!Codex CLI:OpenAI开源终端AI编程助手,代码重构+测试全自动
Codex CLI是OpenAI推出的轻量级AI编程智能体,基于自然语言指令帮助开发者高效生成代码、执行文件操作和进行版本控制,支持代码生成、重构、测试及数据库迁移等功能。
3725 1
自然语言生成代码一键搞定!Codex CLI:OpenAI开源终端AI编程助手,代码重构+测试全自动

热门文章

最新文章