【第09章】【单元测试】

13 篇文章 1 订阅

【第09章-单元测试】


【博文目录>>>】


【工程下载>>>】


ChannelHandler 是Netty 应用程序的关键元素,所以彻底地测试它们应该是你的开发过程的一个标准部分。最佳实践要求你的测试不仅要能够证明你的实现是正确的,而且还要能够很容易地隔离那些因修改代码而突然出现的问题。这种类型的测试叫作单元测试。

虽然单元测试没有统一的定义,但是大多数的从业者都有基本的共识。其基本思想是,以尽可能小的区块测试你的代码,并且尽可能地和其他的代码模块以及运行时的依赖(如数据库和网络)相隔离。如果你的应用程序能通过测试验证每个单元本身都能够正常地工作,那么在出了问题时将可以更加容易地找出根本原因。
在本章中,我们将学习一种特殊的Channel 实现——EmbeddedChannel,它是Netty 专门为改进针对ChannelHandler 的单元测试而提供的。

因为正在被测试的代码模块或者单元将在它正常的运行时环境之外被执行,所以你需要一个框架或者脚手架以便在其中运行它。在我们的例子中,我们将使用JUnit 4 作为我们的测试框架,所以你需要对它的用法有一个基本的了解。如果它对你来说比较陌生,不要害怕;虽然它功能强大,但却很简单,你可以在JUnit 的官方网站(www.junit.org)上找到你所需要的所有信息。

你可能会发现回顾前面关于ChannelHandler 的章节很有用,因为这将为我们的示例提供素材。

9.1 EmbeddedChannel 概述


你已经知道,可以将ChannelPipeline 中的ChannelHandler 实现链接在一起,以构建你的应用程序的业务逻辑。我们已经在前面解释过,这种设计支持将任何潜在的复杂处理过程分解为小的可重用的组件,每个组件都将处理一个明确定义的任务或者步骤。在本章中,我们还将展示它是如何简化测试的。

Netty 提供了它所谓的Embedded 传输,用于测试ChannelHandler。这个传输是一种特殊的Channel 实现—EmbeddedChannel—的功能,这个实现提供了通过ChannelPipeline传播事件的简便方法。

这个想法是直截了当的:将入站数据或者出站数据写入到EmbeddedChannel 中,然后检查是否有任何东西到达了ChannelPipeline 的尾端。以这种方式,你便可以确定消息是否已经被编码或者被解码过了,以及是否触发了任何的ChannelHandler 动作。

表9-1 中列出了EmbeddedChannel 的相关方法。

这里写图片描述

入站数据由ChannelInboundHandler 处理,代表从远程节点读取的数据。出站数据由ChannelOutboundHandler 处理,代表将要写到远程节点的数据。根据你要测试的ChannelHandler,你将使用*Inbound()或者*Outbound()方法对,或者兼而有之。

图9-1 展示了使用EmbeddedChannel 的方法,数据是如何流经ChannelPipeline 的。你可以使用writeOutbound()方法将消息写到Channel 中,并通过ChannelPipeline 沿着出站的方向传递。随后,你可以使用readOutbound()方法来读取已被处理过的消息,以确定结果是否和预期一样。 类似地,对于入站数据,你需要使用writeInbound()和readInbound()方法。

这里写图片描述

在每种情况下,消息都将会传递过ChannelPipeline,并且被相关的ChannelInboundHandler 或者ChannelOutboundHandler 处理。如果消息没有被消费,那么你可以使用readInbound()或者readOutbound()方法来在处理过了这些消息之后,酌情把它们从Channel中读出来。

9.2 使用EmbeddedChannel 测试ChannelHandler

在这一节中,我们将讲解如何使用EmbeddedChannel 来测试ChannelHandler。
JUnit 断言

org.junit.Assert 类提供了很多用于测试的静态方法。失败的断言将导致一个异常被抛出,并将终止当前正在执行中的测试。导入这些断言的最高效的方式是通过一个import static 语句来实现:

import static org.junit.Assert.*;

一旦这样做了,就可以直接调用Assert 方法了:

assertEquals(buf.readSlice(3), read);

9.2.1 测试入站消息


图9-2 展示了一个简单的ByteToMessageDecoder 实现。给定足够的数据,这个实现将产生固定大小的帧。如果没有足够的数据可供读取,它将等待下一个数据块的到来,并将再次检查是否能够产生一个新的帧。

这里写图片描述

正如可以从图9-2 右侧的帧看到的那样,这个特定的解码器将产生固定为3 字节大小的帧。因此,它可能会需要多个事件来提供足够的字节数以产生一个帧。

最终,每个帧都会被传递给ChannelPipeline 中的下一个ChannelHandler。该解码器的实现,如代码清单9-1 所示。

// 代码清单9-1 FixedLengthFrameDecoder
// 扩展ByteToMessageDecoder 以处理入站字节,并将它们解码为消息
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) throws Exception {
        // 检查是否有足够的字节可以被读取,以生成下一个帧
        while (in.readableBytes() >= frameLength) {
            // 从ByteBuf 中读取一个新帧
            ByteBuf buf = in.readBytes(frameLength);
            // 将该帧添加到已被解码的消息列表中
            out.add(buf);
        }
    }
}

现在,让我们创建一个单元测试,以确保这段代码将按照预期执行。正如我们前面所指出的,即使是在简单的代码中,单元测试也能帮助我们防止在将来代码重构时可能会导致的问题,并且能在问题发生时帮助我们诊断它们。

现在,让我们创建一个单元测试,以确保这段代码将按照预期执行。正如我们前面所指出的,即使是在简单的代码中,单元测试也能帮助我们防止在将来代码重构时可能会导致的问题,并且能在问题发生时帮助我们诊断它们。

代码清单9-2 展示了一个使用EmbeddedChannel 的对于前面代码的测试。

// 代码清单9-2 测试FixedLengthFrameDecoder
public class FixedLengthFrameDecoderTest {
    // 使用了注解@Test 标注,因此JUnit 将会执行该方法
    @Test
    // 第一个测试方法:testFramesDecoded()
    public void testFramesDecoded() {
        // 创建一个ByteBuf,并存储9 字节
        ByteBuf buf = Unpooled.buffer();
        for (int i = 0; i < 9; i++) {
            buf.writeByte(i);
        }
        ByteBuf input = buf.duplicate();
        // 创建一个EmbeddedChannel,并添加一个FixedLengthFrameDecoder,其将以3 字节的帧长度被测试
        EmbeddedChannel channel = new EmbeddedChannel(new FixedLengthFrameDecoder(3));

        // write bytes
        // 将数据写入EmbeddedChannel
        assertTrue(channel.writeInbound(input.retain()));
        // 标记Channel为已完成状态
        assertTrue(channel.finish());

        // read messages
        // 读取所生成的消息,并且验证是否有3 帧(切片),其中每帧(切片)都为3 字节
        ByteBuf read = (ByteBuf) channel.readInbound();
        assertEquals(buf.readSlice(3), read);
        read.release();

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

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

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

    @Test
    // 第二个测试方法:testFramesDecoded2()
    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));
        // 返回false,因为没有一个完整的可供读取的帧
        assertFalse(channel.writeInbound(input.readBytes(2)));
        assertTrue(channel.writeInbound(input.readBytes(7)));

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

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

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

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

9.2.2 测试出站消息


测试出站消息的处理过程和刚才所看到的类似。在下面的例子中,我们将会展示如何使用EmbeddedChannel 来测试一个编码器形式的ChannelOutboundHandler,编码器是一种将一种消息格式转换为另一种的组件。你将在下一章中非常详细地学习编码器和解码器,所以现在我们只需要简单地提及我们正在测试的处理器—AbsIntegerEncoder,它是Netty 的MessageToMessageEncoder 的一个特殊化的实现,用于将负值整数转换为绝对值。

该示例将会按照下列方式工作:

  • 持有AbsIntegerEncoder 的EmbeddedChannel 将会以4 字节的负整数的形式写出站数据;

  • 编码器将从传入的ByteBuf 中读取每个负整数,并将会调用Math.abs()方法来获取其绝对值;

  • 编码器将会把每个负整数的绝对值写到ChannelPipeline 中。

图9-3 展示了该逻辑。

这里写图片描述

代码清单9-3 实现了这个逻辑,如图9-3 所示。encode()方法将把产生的值写到一个List 中。

// 代码清单9-3 AbsIntegerEncoder
// 扩展MessageToMessageEncoder 以将一个消息编码为另外一种格式
public class AbsIntegerEncoder extends MessageToMessageEncoder<ByteBuf> {
    @Override
    protected void encode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        // 检查是否有足够的字节用来编码
        while (in.readableBytes() >= 4) {
            // 从输入的ByteBuf中读取下一个整数,并且计算其绝对值
            int value = Math.abs(in.readInt());
            // 将该整数写入到编码消息的List中
            out.add(value);
        }
    }
}

代码清单9-4 使用了EmbeddedChannel 来测试代码。

// 代码清单9-4 测试AbsIntegerEncoder
public class AbsIntegerEncoderTest {
    @Test
    public void testEncoded() {
        // 创建一个ByteBuf,并且写入9 个负整数
        ByteBuf buf = Unpooled.buffer();
        for (int i = 1; i < 10; i++) {
            buf.writeInt(i * -1);
        }

        // 创建一个EmbeddedChannel,并安装一个要测试的AbsIntegerEncoder
        EmbeddedChannel channel = new EmbeddedChannel(new AbsIntegerEncoder());
        // 写入ByteBuf,并断言调用readOutbound()方法将会产生数据
        assertTrue(channel.writeOutbound(buf));
        // 将该Channel标记为已完成状态
        assertTrue(channel.finish());

        // read bytes
        // 读取所产生的消息,并断言它们包含了对应的绝对值
        for (int i = 1; i < 10; i++) {
            assertEquals((Integer) i, (Integer) channel.readOutbound());
        }
        assertNull(channel.readOutbound());
    }
}

下面是代码中执行的步骤。

(1) 将4 字节的负整数写到一个新的ByteBuf 中。

(2) 创建一个EmbeddedChannel,并为它分配一个AbsIntegerEncoder。

(3) 调用EmbeddedChannel 上的writeOutbound()方法来写入该ByteBuf。

(4) 标记该Channel 为已完成状态。

(5) 从EmbeddedChannel 的出站端读取所有的整数,并验证是否只产生了绝对值。

9.3 测试异常处理


应用程序通常需要执行比转换数据更加复杂的任务。例如,你可能需要处理格式不正确的输入或者过量的数据。在下一个示例中,如果所读取的字节数超出了某个特定的限制,我们将会抛出一个TooLongFrameException。这是一种经常用来防范资源被耗尽的方法。

在图9-4 中,最大的帧大小已经被设置为3 字节。如果一个帧的大小超出了该限制,那么程序将会丢弃它的字节,并抛出一个TooLongFrameException。位于ChannelPipeline 中的其他ChannelHandler 可以选择在exceptionCaught()方法中处理该异常或者忽略它。

这里写图片描述

其实现如代码清单9-5 所示。

// 代码清单9-5 FrameChunkDecoder
// 扩展ByteToMessageDecoder 以将入站字节解码为消息
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)
            throws Exception {
        int readableBytes = in.readableBytes();
        // 如果该帧太大,则丢弃它并抛 出一个TooLongFrameException
        if (readableBytes > maxFrameSize) {
            // discard the bytes
            in.clear();
            throw new TooLongFrameException();
        }
        // 否则,从ByteBuf 中读取一个新的帧
        ByteBuf buf = in.readBytes(readableBytes);
        // 将该帧添加到解码消息的List 中
        out.add(buf);
    }
}

我们再使用EmbeddedChannel 来测试一次这段代码,如代码清单9-6 所示。

// 代码清单9-6 测试FrameChunkDecoder
public class FrameChunkDecoderTest {
    @Test
    public void testFramesDecoded() {
        // 创建一个ByteBuf,并向它写入9 字节
        ByteBuf buf = Unpooled.buffer();
        for (int i = 0; i < 9; i++) {
            buf.writeByte(i);
        }
        ByteBuf input = buf.duplicate();

        // 创建一个EmbeddedChannel,并向其安装一个帧大小为3 字节的FixedLengthFrameDecoder
        EmbeddedChannel channel = new EmbeddedChannel(new FrameChunkDecoder(3));

        // 向它写入2 字节,并断言它们将会产生一个新帧
        assertTrue(channel.writeInbound(input.readBytes(2)));
        try {
            // 写入一个4 字节大小的帧,并捕获预期的TooLongFrameException
            channel.writeInbound(input.readBytes(4));
            // 如果上面没有抛出异常,那么就会到达这个断言,并且测试失败
            Assert.fail();
        } catch (TooLongFrameException e) {
            // expected exception
        }

        // 写入剩余的2 字节,并断言将会产生一个有效帧
        assertTrue(channel.writeInbound(input.readBytes(3)));
        // 将该Channel 标记为已完成状态
        assertTrue(channel.finish());

        // Read frames
        // 读取产 生的消息,并且验证值
        ByteBuf read = (ByteBuf) channel.readInbound();
        assertEquals(buf.readSlice(2), read);
        read.release();

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

乍一看,这看起来非常类似于代码清单9-2 中的测试,但是它有一个有趣的转折点,即对TooLongFrameException的处理。这里使用的try/catch块是EmbeddedChannel的一个特殊功能。如果其中一个write*方法产生了一个受检查的Exception,那么它将会被包装在一个RuntimeException中并抛出,需要注意的是,如果该类实现了exceptionCaught()方法并处理了该异常,那么它将不会被catch块所捕获。这使得可以容易地测试出一个Exception是否在处理数据的过程中已经被处理了。这里介绍的测试方法可以用于任何能抛出Exception 的ChannelHandler 实现。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值