netty实战笔记 第九章 单元测试
9.1 EmbeddedChannel 概述
netty提供了Embedded传输,用于测试ChannelHandler. 这个服传输是一种特殊的Channel实现,EmbeddedChannel的功能,这个实现提供了通过ChannelPipeline传播事件的简便方法。
具体的思路是:将入站数据或者出站数据写到EmbeddedChannel中,然后检查是否有任何东西到达了ChannelPipeline的尾端。这样便可以确定消息是否已经被Handler处理。
下面是EmbeddedChannel的API
方法名称 | 作用 |
---|---|
writeInbound(Object… msgs) | 将入站消息写到EmbeddedChannel 中。如果可以通过readInbound()方法从EmbeddedChannel 中读取数据,则返回true |
readInbound() | 从EmbeddedChannel 中读取一个入站消息。任何返回的东西都穿越了整个ChannelPipeline。如果没有任何可供读取的,则返回null |
writeOutbound(Object… msgs) | 将出站消息写到EmbeddedChannel中。如果现在可以通过readOutbound()方法从EmbeddedChannel 中读取到什么东西,则返回true |
readOutbound() | 从EmbeddedChannel 中读取一个出站消息。任何返回的东西都穿越了整个ChannelPipeline。如果没有任何可供读取的,则返回null |
finish() | 将EmbeddedChannel 标记为完成,并且如果有可被读取的入站数据或者出站数据,则返回true。这个方法还将会调用EmbeddedChannel |
入站数据由ChannelInboundHandler 处理,代表从远程节点读取的数据。出站数据由ChannelOutboundHandler 处理,代表将要写到远程节点的数据。
看下EmbeddedChannel的数据流图
在每种情况下,消息都将会传递过ChannelPipeline,并且被相关的ChannelInboundHandler 或者hannelOutboundHandler 处理。如果消息没有被消费,那么你可以使用readInbound()或者readOutbound()方法来在处理过了这些消息之后,酌情把它们从Channel中读出来。
9.2 使用EmbeddedChannel测试ChannelHandler
9.2.1 测试入站消息
使用Demo:
package com.moyang3.testInbound;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import java.util.List;
public class FixedLengthFrameDecoder extends ByteToMessageDecoder {
private final int frameLength;
public FixedLengthFrameDecoder (int frameLength) {
if(frameLength < 0) {
throw new IllegalArgumentException("!!!!");
}
this.frameLength = frameLength;
}
protected void decode (ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
while(byteBuf.readableBytes() >= frameLength) {
ByteBuf buf = byteBuf.readBytes(frameLength);
list.add(buf);
}
}
}
package com.moyang3.testInbound;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.FixedLengthFrameDecoder;
public class FixedLengthFrameDecoderTest {
public void testFramesDecoded () {
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));
assert channel.writeInbound(input.retain());
assert(channel.finish());
}
}
9.2.3 测试出站消息
略。
最后
如果你觉得写的还不错,就关注下公众号呗,关注后,有点小礼物回赠给你。
你可以获得5000+电子书,java,springCloud,adroid,python等各种视频教程,IT类经典书籍,各种软件的安装及破解教程。
希望一块学习,一块进步!
还没有评论,来说两句吧...