Netty单元测试

感慨

一晃两年多了,自从刚开始给公司编写的几个网络模块,后来就没有在度使用的机会了。
讲解Netty的书籍有许多,其中《Netty实战》这本书比较经典,推荐大家用这本书入门。

概述

工欲善其事,必先利其器。
作为一个网络处理框架,如果没有脱离网络的单元测试,那么你要构建完整的一套代码,方能测试相应功能,是无法想象的。
ChannelHandler 是 Netty 应用程序的关键元素,无非就是处理输入数据,然后输出处理结果。
EmbeddedChannel,它是 Netty 专门为改进针对 ChannelHandler 的单元测试而提供的。它在设计上包含的关键方法,正是针对数据输入、数据输出的。

参考链接

https://blog.csdn.net/ljz2016/article/details/82899550
《netty实战》第9章

示例

目标:输入为大写字母,输出为小写字母。

处理器代码

public class TestDecoder extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        byte[] readByte = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(readByte);
        for (int i = 0; i < readByte.length; i++) {
            readByte[i] += 32;//大写转小写
        }
        list.add(readByte);
    }
}

测试代码

    @Test
    public void test001() {
        ByteBuf buf = Unpooled.buffer();

        buf.writeByte("A".getBytes()[0]);
        buf.writeByte("B".getBytes()[0]);
        buf.writeByte("C".getBytes()[0]);

        ByteBuf input = buf.duplicate();
        EmbeddedChannel channel = new EmbeddedChannel(new TestDecoder());
        assertTrue(channel.writeInbound(input.retain()));
        assertTrue(channel.finish());


        //读取消息
        byte[] readByte = channel.readInbound();
        System.out.println("" + new String(readByte));
    }

运行效果

打印出

abc
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值