DotNetty完全教程(十)

单元测试

EmbeddedChannel介绍

EmbeddedChannel是专门为了测试ChannelHandler的传输。我们先看一下他的API
DotNetty完全教程(十)_第1张图片
用一张图来描述这样的一个模拟过程
DotNetty完全教程(十)_第2张图片

编写基于xUnit的单元测试

  1. 新建一个xUnit工程 UnitTest
  2. 新建一个用于测试EmbededChannel的工程 EmbededChannelTest
  3. EmbededChannelTest工程需要引用DotNetty的类库,这里因为我们需要测试一个解码器,所以除了原先的Buffer Common Transport之外我们还需要引用Codecs
  4. xUnit工程需要引用EmbededChannelTest工程
  5. 在EmbededChannelTest工程之下新建FixedLengthFrameDecoder待测试类
using DotNetty.Buffers;
using DotNetty.Codecs;
using DotNetty.Transport.Channels;
using System;
using System.Collections.Generic;
using System.Text;

namespace EmbededChannelTest
{
    public class FixedLengthFrameDecoder : ByteToMessageDecoder
    {
        private int _frameLength;
        public FixedLengthFrameDecoder(int frameLength)
        {
            if (frameLength <= 0)
            {
                throw new Exception("不合法的参数。");
            }
            _frameLength = frameLength;
        }
        protected override void Decode(IChannelHandlerContext context, IByteBuffer input, List output)
        {
            // 解码器实现固定的帧长度
            while (input.ReadableBytes >= _frameLength)
            {
                IByteBuffer buf = input.ReadBytes(_frameLength);
                output.Add(buf);
            }
        }
    }
}

我们可以看到这个解码器将buffer中的字节流转化为每3个一帧。接下来我们需要编写测试类,我们在UnitTest工程下新建一个类,名字叫做UnitTester,编写如下代码:

using DotNetty.Buffers;
using DotNetty.Transport.Channels.Embedded;
using EmbededChannelTest;
using System;
using System.Collections.Generic;
using System.Text;
using Xunit;

namespace UnitTest
{
    public class UnitTester
    {
        [Fact]
        public void testFrameDecoder()
        {
            IByteBuffer buf = Unpooled.Buffer();
            for (int i = 0; i < 9; i++)
            {
                buf.WriteByte(i);
            }
            IByteBuffer input = buf.Duplicate();
            EmbeddedChannel channel = new EmbeddedChannel(new FixedLengthFrameDecoder(3));
            // 写数据
            // retain能够将buffer的引用计数加1,并且返回这个buffer本身
            Assert.True(channel.WriteInbound(input.Retain()));
            Assert.True(channel.Finish());
            // 读数据
            IByteBuffer read = channel.ReadInbound();
            Assert.Equal(buf.ReadSlice(3), read);
            read.Release();

            read = channel.ReadInbound();
            Assert.Equal(buf.ReadSlice(3), read);
            read.Release();

            read = channel.ReadInbound();
            Assert.Equal(buf.ReadSlice(3), read);
            read.Release();

            Assert.Null(channel.ReadInbound());
            buf.Release();
        }
    }
}

编写完成之后直接右键点击运行测试即可。同理我们可以测试用于出站数据的Encoder,这里不贴代码了,感兴趣的可以去工程中自己看源码进行学习。

你可能感兴趣的:(DotNetty,C#)