如何为 Netty 新增编解码器编写单元测试?
解读
在国内一线互联网公司的面试中,这道题并不是“写个 JUnit 就完事”的送分题,而是考察候选人是否真正理解 Netty 的 pipeline 机制、内存模型、零拷贝以及“一次编写、随处运行”的稳定性要求。
面试官期望听到:
- 测试用例必须覆盖“半包、粘包、字节序、内存泄漏、异常传播”五种典型场景;
- 不依赖真实网卡,使用 EmbeddedChannel 完成毫秒级回归;
- 通过池化 ByteBuf 的引用计数断言,确保零拷贝逻辑没有忘记 release;
- 在 CI 环境可重复运行,Linux、Windows、Mac 结果一致;
- 给出性能基线(如 QPS、单次 encode/decode 耗时)的自动化对比方式,防止后续提交劣化。
如果候选人只回答“我 new 一个 EmbeddedChannel,写进去再读出来”,会被直接判定为“只用过 Demo,没上过生产”。
知识点
- EmbeddedChannel 原理:内部维护一对队列(inboundMessages/outboundMessages),不触发系统调用,适合单元层。
- ByteBuf 引用计数规则:谁最后访问谁负责 release;测试里必须用 ReferenceCountUtil.releaseLater 或 SimpleLeakDetector 做断言。
- 半包/粘包模拟:通过“分两次写入”“一次写入 N 倍报文”两种手段触发 Decoder 的 cumulation 逻辑。
- 异常传播链:writeInbound 抛出 DecoderException 时,需验证 cause 是否为预期异常,且 pipeline 仍可用。
- 内存池泄漏检测:启动测试时加 -Dio.netty.leakDetection.level=paranoid,在 @AfterEach 中强制 System.gc() 两次,再用 assertThat(LeakDetector.getLeakCount()).isZero()。
- 性能基线:使用 JMH 编写 micro-benchmark,以 ops/us 为单位,配合 github-action 的“持续性能门禁”脚本,当退化超过 5% 自动打回。
- 兼容性矩阵:在 CI 里同时跑 Netty4.1.x 与 Netty5.0-alpha,确保编解码器未来可平滑升级。
答案
下面给出一套可直接落地到国内 Maven 工程的完整方案,覆盖“功能正确性 + 内存安全 + 性能基线”三个维度。
一、功能正确性测试(基于 EmbeddedChannel)
public final class MyProtocolCodecTest {
private final EmbeddedChannel channel = new EmbeddedChannel(new MyLengthFieldDecoder(), new MyBodyDecoder());
@Test
public void testFullPacket() {
ByteBuf buf = Unpooled.buffer();
buf.writeInt(8); // length
buf.writeLong(0x12345678L);// body
assertTrue(channel.writeInbound(buf));
assertEquals(0x12345678L, channel.readInbound());
assertNull(channel.readInbound()); // 无残留
}
@Test
public void testHalfPacket() {
ByteBuf buf1 = Unpooled.buffer();
buf1.writeInt(8);
ByteBuf buf2 = Unpooled.buffer();
buf2.writeLong(0x12345678L);
assertFalse(channel.writeInbound(buf1)); // 半包,不会触发 decode
assertTrue(channel.writeInbound(buf2)); // 凑齐后触发
assertEquals(0x12345678L, channel.readInbound());
}
@Test
public void testStickyPacket() {
ByteBuf buf = Unpooled.buffer();
buf.writeInt(8).writeLong(1L)
.writeInt(8).writeLong(2L);
assertTrue(channel.writeInbound(buf));
assertEquals(1L, channel.readInbound());
assertEquals(2L, channel.readInbound());
assertNull(channel.readInbound());
}
@AfterEach
public void tearDown() {
assertFalse(channel.finish()); // 确保无泄漏
}
}
二、内存安全测试( paranoid 级别泄漏检测)
@ExtendWith(NettyLeakExtension.class)
class MyCodecLeakTest {
@Test
void noLeakWhenException() {
EmbeddedChannel ch = new EmbeddedChannel(new MyDecoder());
ByteBuf buf = Unpooled.wrappedBuffer(new byte[]{1,2,3}); // 非法报文
assertThrows(Exception.class, () -> ch.writeInbound(buf));
// NettyLeakExtension 会在 @AfterEach 中断言 leakCount == 0
}
}
其中 NettyLeakExtension 在 beforeAll 时设置 System.setProperty("io.netty.leakDetection.level", "paranoid"),并在 afterEach 中触发 gc 与计数断言。
三、性能基线测试(JMH)
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@Warmup(iterations = 3, time = 1)
@Measurement(iterations = 5, time = 1)
@Fork(1)
public class MyCodecBenchmark {
private final EmbeddedChannel channel = new EmbeddedChannel(new MyEncoder());
private final ByteBuf payload = Unpooled.wrappedBuffer(new byte[1024]);
@Benchmark
public Object encode1024() {
channel.writeOutbound(payload.retainedDuplicate());
return channel.readOutbound();
}
}
在 CI 中通过 github-action 运行,并将结果推送到性能看板,若下降超过 5% 自动打回 PR。
四、覆盖率与回归策略
使用 maven-surefire + jacoco,要求 instruction 覆盖率 ≥ 90%,branch 覆盖率 ≥ 85%。每次 master 合并前跑全量单测 + JMH,耗时控制在 3 min 内,满足国内“日构建千次”节奏。
拓展思考
-
如果编解码器需要支持协议版本升级,如何设计向前兼容的测试?
答:在 resources 目录下预置“历史版本二进制 dump”,用参数化测试(@ParameterizedTest)一次性喂给新版本解码器,断言能正确识别并升级字段。 -
当 ChannelPipeline 动态变化(热插拔)时,如何保证测试稳定性?
答:使用 ChannelInitializer 的 @Shareable 单例,并在测试线程里通过 CountDownLatch 等待 pipeline 修改事件(ChannelPipelineListener),确保断言发生在“可见”之后。 -
国内很多厂用 ARM 服务器,字节序或内存对齐差异可能导致绿幕测试通过、生产异常,如何在单元测试阶段发现?
答:在 CI 矩阵里加入 aarch64 容器(如华为云 Kunpeng),并在测试用例里显式切换 ByteOrder.LITTLE_ENDIAN 与 BIG_ENDIAN,双重验证。 -
对于高吞吐网关场景,编解码器往往与内存池、对象池一起使用,如何验证“对象回池”逻辑正确?
答:在 @Benchmark 模式外再跑一个“压力+内存采样”模式,使用 async-profiler 的 alloc 事件采样,断言分配速率低于基线 10%,否则判定回池失败。