Skip to content

第 9 章:单元测试(Unit Testing) ​

在《Netty in Action》第 9 章中,作者 Norman Maurer 聚焦于一个在工程实践中极易被忽视却至关重要的主题——如何对 ChannelHandler 进行高效、可靠的单元测试。

ChannelHandler 是 Netty 应用中承载核心业务逻辑的组件(如协议编解码、帧切分、业务路由与异常拦截等)。如果缺少针对性的单元测试,我们往往只能在集成测试甚至生产环境中才能暴露协议解析边界错误或内存泄漏问题。本章围绕 Netty 专门提供的测试工具 EmbeddedChannel,系统讲解如何在不依赖真实网络和多线程的前提下,对入站、出站及异常处理逻辑进行全面测试。


1. 为什么对 ChannelHandler 进行单元测试很重要? ​

1.1 传统网络代码测试的痛点 ​

在没有专用测试工具的情况下,测试网络应用通常意味着必须启动真实的服务端与客户端,这会带来一系列棘手的问题:

  1. 依赖真实套接字与端口:测试用例需要绑定本地端口,在并发执行测试或 CI/CD 环境中极易发生端口冲突(BindException)。
  2. 异步与多线程不可控:真实的网络 I/O 运行在独立的 EventLoop 线程中,测试线程需要等待异步结果。开发者往往被迫使用 Thread.sleep() 或复杂的 CountDownLatch 来同步,导致测试运行缓慢且容易出现偶发失败(Flaky Tests)。
  3. 难以隔离单个 ChannelHandler:在完整的服务端/客户端链路中测试某一个编解码器时,任何上下游组件的异常或网络抖动都会干扰定位。
  4. 边界场景构造困难:例如 TCP 拆包(一个完整消息分多次到达)、粘包(多个消息一次到达)或特定字节触发的异常,在真实网络环境下很难稳定复现。

1.2 Netty 的解决方案 ​

为了消除上述痛点,Netty 提供了 EmbeddedChannel。它允许我们在单线程、零网络开销的环境中,像操纵普通集合一样向 ChannelPipeline 注入数据并立即读取处理结果,从而让 ChannelHandler 的单元测试变得像测试普通 Java 类一样简单、快速且确定。


2. EmbeddedChannel 的核心设计思想与工作原理 ​

EmbeddedChannel(位于 io.netty.channel.embedded 包)是 io.netty.channel.Channel 接口的一个特殊实现。它的核心设计思想是**“在内存中模拟一条完整的 ChannelPipeline 数据通路”**。

2.1 内部机制 ​

  • 无真实网络传输:EmbeddedChannel 不绑定任何底层的 Socket,也不进行任何系统级 I/O 调用。
  • 同步执行模型:它内部使用 EmbeddedEventLoop,所有写入操作(入站或出站)都会在当前测试线程中同步执行,一旦 writeInbound() 或 writeOutbound() 返回,整个 ChannelPipeline 的处理就已经完成,无需任何等待或线程同步。
  • 双队列缓冲:EmbeddedChannel 内部维护了两个队列,分别用于暂存流经 ChannelPipeline 后产出的结果:
    • 入站消息队列(inboundMessages):存放经过所有 ChannelInboundHandler 处理后到达 Pipeline 末端的消息。
    • 出站消息队列(outboundMessages):存放经过所有 ChannelOutboundHandler 处理后到达 Pipeline 末端的消息。

2.2 数据流向示意图 ​

EmbeddedChannel 内部结构与数据流向示意图

通过这种设计:

  • 测试入站处理器时,调用 writeInbound() 模拟从远端接收到字节/消息,再调用 readInbound() 取出处理器输出的结果进行断言。
  • 测试出站处理器时,调用 writeOutbound() 模拟应用层向下写出消息,再调用 readOutbound() 取出编码/转换后的结果进行断言。

3. EmbeddedChannel 的关键 API ​

下表汇总了单元测试中最常用的 EmbeddedChannel 方法:

方法签名作用说明返回值语义
boolean writeInbound(Object... msgs)将一个或多个入站消息写入 EmbeddedChannel,触发入站事件流经 Pipeline。如果写入后 inboundMessages 队列中至少有一条消息可读(即 readInbound() 不为 null),返回 true;否则返回 false。
<T> T readInbound()从 inboundMessages 队列头部取出一条已处理的入站消息。队列非空时返回消息对象;队列为空时返回 null。
boolean writeOutbound(Object... msgs)将一个或多个出站消息写入 EmbeddedChannel,触发出站事件流经 Pipeline。如果写入后 outboundMessages 队列中至少有一条消息可读,返回 true;否则返回 false。
<T> T readOutbound()从 outboundMessages 队列头部取出一条已处理的出站消息。队列非空时返回消息对象;队列为空时返回 null。
boolean finish()将 EmbeddedChannel 标记为已完成(触发关闭事件)。调用后不能再写入数据,但仍可读取队列中残留的消息。如果 inboundMessages 或 outboundMessages 中仍有未读取的数据,返回 true;否则返回 false。
boolean finishAndReleaseAll()标记通道完成,并自动释放队列中所有尚未读取的引用计数对象(如 ByteBuf),防止测试产生内存泄漏。如果在释放前至少有一个队列非空,返回 true;否则返回 false。
Queue<Object> inboundMessages()返回底层存储入站消息的队列引用。Queue<Object>,可用于检查剩余消息数量等。
Queue<Object> outboundMessages()返回底层存储出站消息的队列引用。Queue<Object>,可用于检查剩余消息数量等。

TIP

注意区分 writeInbound() 的返回值含义:它返回 true 并不代表写入成功,而是代表“本次写入之后,入站队列里有数据可供 readInbound() 读取”。在测试拆包场景(半包写入暂未凑成完整一帧)时,writeInbound() 返回 false 反而是符合预期的!


4. 测试入站消息:FixedLengthFrameDecoder ​

4.1 待测组件实现 ​

假设我们需要一个按固定长度(例如每帧 3 字节)切分字节流的入站解码器 FixedLengthFrameDecoder,它继承自 ByteToMessageDecoder:

java
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import java.util.List;

public class FixedLengthFrameDecoder extends ByteToMessageDecoder {
    private final int frameLength;

    public FixedLengthFrameDecoder(int frameLength) {
        if (frameLength <= 0) {
            throw new IllegalArgumentException(
                "frameLength must be a positive integer: " + frameLength);
        }
        this.frameLength = frameLength;
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
        // 只要当前可读字节数达到指定帧长,就切分出一帧
        while (in.readableBytes() >= frameLength) {
            ByteBuf buf = in.readBytes(frameLength);
            out.add(buf);
        }
    }
}

4.2 编写单元测试(完整帧写入 & 分片拆包写入) ​

在测试入站解码器时,我们需要覆盖两种核心场景:

  1. 一次性写入完整多帧(testFramesDecoded):写入 9 字节,验证能连续读出 3 个 3 字节的帧。
  2. 分片拆包写入(testFramesDecoded2):先写入 2 字节(不足 3 字节,不应产生输出),再写入剩余 7 字节,验证解码器能正确缓存半包并最终输出 3 个完整帧。
java
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.embedded.EmbeddedChannel;
import org.junit.Test;

import static org.junit.Assert.*;

public class FixedLengthFrameDecoderTest {

    @Test
    public void testFramesDecoded() {
        // 1. 构造 9 字节的测试数据(0 ~ 8)
        ByteBuf buf = Unpooled.buffer();
        for (int i = 0; i < 9; i++) {
            buf.writeByte(i);
        }
        ByteBuf input = buf.duplicate();

        // 2. 创建 EmbeddedChannel 并装配待测解码器
        EmbeddedChannel channel = new EmbeddedChannel(new FixedLengthFrameDecoder(3));

        // 3. 写入入站数据。注意调用 retain(),因为 writeInbound 处理后可能会释放传入的 ByteBuf,
        //    而我们后面还要使用原始 buf 进行切片比对
        assertTrue(channel.writeInbound(input.retain()));
        assertTrue(channel.finish());

        // 4. 逐帧读取并验证内容,每读出一帧后务必释放资源
        ByteBuf read = channel.readInbound();
        assertEquals(buf.readSlice(3), read);
        read.release();

        read = channel.readInbound();
        assertEquals(buf.readSlice(3), read);
        read.release();

        read = channel.readInbound();
        assertEquals(buf.readSlice(3), read);
        read.release();

        // 5. 确认队列已空,并释放原始缓冲区
        assertNull(channel.readInbound());
        buf.release();
    }

    @Test
    public void testFramesDecoded2() {
        ByteBuf buf = Unpooled.buffer();
        for (int i = 0; i < 9; i++) {
            buf.writeByte(i);
        }
        ByteBuf input = buf.duplicate();

        EmbeddedChannel channel = new EmbeddedChannel(new FixedLengthFrameDecoder(3));

        // 先写入 2 字节(不足 3 字节),此时不会产出完整帧,writeInbound 应返回 false
        assertFalse(channel.writeInbound(input.readBytes(2)));
        // 再写入剩余 7 字节,凑齐 9 字节,应产出 3 帧,writeInbound 返回 true
        assertTrue(channel.writeInbound(input.readBytes(7)));

        assertTrue(channel.finish());

        ByteBuf read = channel.readInbound();
        assertEquals(buf.readSlice(3), read);
        read.release();

        read = channel.readInbound();
        assertEquals(buf.readSlice(3), read);
        read.release();

        read = channel.readInbound();
        assertEquals(buf.readSlice(3), read);
        read.release();

        assertNull(channel.readInbound());
        buf.release();
    }
}

IMPORTANT

为什么 testFramesDecoded() 中需要 input.retain() 和 read.release()?

  • ByteToMessageDecoder 在消费完传入的 ByteBuf 后会自动调用 release()。由于 input 是 buf.duplicate() 出来的视图,它们共享同一个引用计数。如果不先 retain(),写入之后引用计数会归零,后续 buf.readSlice(3) 就会抛出 IllegalReferenceCountException。
  • 通过 readInbound() 读出的每一帧 ByteBuf 同样带有引用计数,断言完毕后调用 read.release() 是避免内存泄漏的必要习惯。

5. 测试出站消息:AbsIntegerEncoder ​

5.1 待测组件实现 ​

接下来看一个出站编码器的例子:AbsIntegerEncoder(继承自 MessageToMessageEncoder<ByteBuf>)。它从出站 ByteBuf 中按 4 字节读取整数,将其转换为绝对值后作为 Integer 对象写入出站列表:

java
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import java.util.List;

public class AbsIntegerEncoder extends MessageToMessageEncoder<ByteBuf> {
    @Override
    protected void encode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
        // 只要还有足够的字节构成一个 int(4 字节),就读取并转为绝对值
        while (in.readableBytes() >= 4) {
            int value = Math.abs(in.readInt());
            out.add(value);
        }
    }
}

5.2 编写单元测试 ​

测试出站逻辑的套路与入站对称:写入负整数构成的 ByteBuf 到 writeOutbound(),再通过 readOutbound() 逐个读取并断言是否都变为了正整数。

java
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.embedded.EmbeddedChannel;
import org.junit.Test;

import static org.junit.Assert.*;

public class AbsIntegerEncoderTest {

    @Test
    public void testEncoded() {
        // 1. 构造包含 9 个负整数(-1 到 -9)的 ByteBuf
        ByteBuf buf = Unpooled.buffer();
        for (int i = 1; i < 10; i++) {
            buf.writeInt(i * -1);
        }

        // 2. 创建装配了 AbsIntegerEncoder 的 EmbeddedChannel
        EmbeddedChannel channel = new EmbeddedChannel(new AbsIntegerEncoder());

        // 3. 写入出站数据并结束通道
        assertTrue(channel.writeOutbound(buf));
        assertTrue(channel.finish());

        // 4. 逐个读取编码后的 Integer 对象并验证绝对值结果
        for (int i = 1; i < 10; i++) {
            assertEquals(Integer.valueOf(i), channel.readOutbound());
        }
        assertNull(channel.readOutbound());
    }
}

NOTE

在本例中,writeOutbound(buf) 内部由 MessageToMessageEncoder 负责释放传入的 buf,而 readOutbound() 读出的是普通 Integer 对象(非 ReferenceCounted),因此不需要对读出的结果调用 release()。


6. 测试异常处理:FrameChunkDecoder ​

在真实协议处理中,防范恶意超大报文(防止 OOM)是常见需求。当入站帧长度超过预设上限时,处理器通常会丢弃非法数据并抛出 TooLongFrameException。EmbeddedChannel 可以直接将 Pipeline 中未捕获的异常重新抛回到测试调用方,使我们能够轻松使用 try-catch 进行断言。

6.1 待测组件实现 ​

java
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.TooLongFrameException;
import java.util.List;

public class FrameChunkDecoder extends ByteToMessageDecoder {
    private final int maxFrameSize;

    public FrameChunkDecoder(int maxFrameSize) {
        this.maxFrameSize = maxFrameSize;
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
        int readableBytes = in.readableBytes();
        if (readableBytes > maxFrameSize) {
            // 超过最大允许帧长:丢弃当前缓冲区中的字节,并抛出异常
            in.clear();
            throw new TooLongFrameException();
        }
        ByteBuf buf = in.readBytes(readableBytes);
        out.add(buf);
    }
}

6.2 编写异常断言测试 ​

我们构造一个总长 9 字节的缓冲区,并分三次写入:

  1. 写入 2 字节(合法,正常输出)。
  2. 写入 4 字节(超过 maxFrameSize = 3,预期抛出 TooLongFrameException)。
  3. 写入剩余 3 字节(合法,验证抛出异常后解码器仍能恢复正常状态并继续工作)。
java
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.TooLongFrameException;
import org.junit.Assert;
import org.junit.Test;

import static org.junit.Assert.*;

public class FrameChunkDecoderTest {

    @Test
    public void testFramesDecoded() {
        ByteBuf buf = Unpooled.buffer();
        for (int i = 0; i < 9; i++) {
            buf.writeByte(i);
        }
        ByteBuf input = buf.duplicate();

        // 设置最大帧长为 3 字节
        EmbeddedChannel channel = new EmbeddedChannel(new FrameChunkDecoder(3));

        // 第 1 次写入:2 字节,正常解码
        assertTrue(channel.writeInbound(input.readBytes(2)));

        // 第 2 次写入:4 字节,超出上限,预期抛出 TooLongFrameException
        try {
            channel.writeInbound(input.readBytes(4));
            // 如果没有抛出异常,则测试失败
            Assert.fail();
        } catch (TooLongFrameException e) {
            // 符合预期的异常
        }

        // 第 3 次写入:3 字节,验证异常之后解码器仍能正常工作
        assertTrue(channel.writeInbound(input.readBytes(3)));
        assertTrue(channel.finish());

        // 读取并验证第 1 帧(2 字节)
        ByteBuf read = channel.readInbound();
        assertEquals(buf.readSlice(2), read);
        read.release();

        // 跳过中间被丢弃的 4 字节,读取并验证第 2 帧(3 字节)
        read = channel.readInbound();
        assertEquals(buf.skipBytes(4).readSlice(3), read);
        read.release();

        assertNull(channel.readInbound());
        buf.release();
    }
}

TIP

在第 2 次写入中,如果 FrameChunkDecoder 的异常是在 ByteToMessageDecoder 内部捕获并重新抛出的,input.readBytes(4) 产生的临时 ByteBuf 会由 ByteToMessageDecoder 释放。验证测试结束时通过 buf.release() 确保初始缓冲区引用计数归零。


7. 单元测试最佳实践与资源管理注意事项 ​

在实际项目中使用 EmbeddedChannel 编写单元测试时,建议遵循以下最佳实践:

  1. 严格管理引用计数,防止内存泄漏

    • 所有从 readInbound() 或 readOutbound() 取出的 ByteBuf(或其他实现了 ReferenceCounted 的对象),在断言完成后必须显式调用 release()(或使用 ReferenceCountUtil.release(msg))。
    • 如果原始测试 ByteBuf 在传入 writeInbound() / writeOutbound() 之后仍需在测试代码中使用(如通过 readSlice() 比对内容),务必提前调用 retain(),并在测试末尾调用 release()。
    • 优先使用 finishAndReleaseAll():在不需要逐一读取剩余消息、或作为测试 finally / @After 清理逻辑时,调用 channel.finishAndReleaseAll() 可以自动释放队列中残留的所有引用计数对象。
    • 在运行测试套件时,建议加上 JVM 参数 -Dio.netty.leakDetection.level=PARANOID,以便在开发阶段第一时间捕获任何潜在的 ByteBuf 泄漏。
  2. 保持测试之间的状态隔离

    • 每个测试方法都应创建独立的 EmbeddedChannel 实例,避免多个测试用例共享同一个有状态的 ChannelHandler 实例(除非该 Handler 明确标注了 @Sharable 且是线程安全/无状态的)。
  3. 全面覆盖协议边界与异常恢复

    • 拆包测试:逐字节或分片写入(验证 writeInbound() 返回 false 直到凑够完整帧)。
    • 粘包测试:一次写入多帧数据,验证能循环 readInbound() 读出全部预期消息。
    • 异常后恢复测试:不仅要断言抛出了预期的异常,还应像 FrameChunkDecoderTest 那样继续写入合法数据,验证 ChannelHandler 内部状态没有被破坏。
  4. 注意 writeInbound() / writeOutbound() 的可变参数行为

    • 这两个方法接收 Object... msgs,会按顺序逐个将消息送入 Pipeline。只要其中任意一条消息产生了到达队列末端的输出,方法就会返回 true。如果需要精确断言每一条输入的输出情况,建议拆分成多次单条写入调用。