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
发布了16 篇原创文章 · 获赞 1 · 访问量 3587

猜你喜欢

转载自blog.csdn.net/a215095167/article/details/104905170