我最近与Netty进行了一些合作,并且按照此出色的教程中的说明构建了编码器/解码器管道,以测试编码器和解码器是否在正常工作而不必发送真实的消息。
幸运的是,有一个EmbeddedChannel确实使我们的生活变得非常轻松。
假设我们有一条消息“ Foo”,我们想通过网络发送。 它仅包含一个整数值,因此我们只需要发送该值并在另一侧重建“ Foo”即可。
我们可以编写以下编码器来执行此操作:
// Examples uses Netty 4.0.28.Final
public static class MessageEncoder extends MessageToMessageEncoder<Foo>
{@Overrideprotected void encode( ChannelHandlerContext ctx, Foo msg, List<Object> out ) throws Exception{ByteBuf buf = ctx.alloc().buffer();buf.writeInt( msg.value() );out.add( buf );}
}public static class Foo
{private Integer value;public Foo(Integer value){this.value = value;}public int value(){return value;}
}
因此,我们要做的就是从“ Foo”中取出“ value”字段,并将其放入要传递到下游的列表中。
让我们编写一个测试,该测试模拟发送“ Foo”消息并使用空的解码器尝试处理该消息:
@Test
public void shouldEncodeAndDecodeVoteRequest()
{// givenEmbeddedChannel channel = new EmbeddedChannel( new MessageEncoder(), new MessageDecoder() );// whenFoo foo = new Foo( 42 );channel.writeOutbound( foo );channel.writeInbound( channel.readOutbound() );// thenFoo returnedFoo = (Foo) channel.readInbound();assertNotNull(returnedFoo);assertEquals( foo.value(), returnedFoo.value() );
}public static class MessageDecoder extends MessageToMessageDecoder<ByteBuf>
{@Overrideprotected void decode( ChannelHandlerContext ctx, ByteBuf msg, List<Object> out ) throws Exception { }
}
因此,在测试中,我们将“ Foo”写入出站通道,然后将其读回入站通道,然后检查所获得的内容。 如果现在运行该测试,将会看到以下内容:
junit.framework.AssertionFailedErrorat NettyTest.shouldEncodeAndDecodeVoteRequest(NettyTest.java:28)
我们返回的消息为空,这是有意义的,因为我们不必费心编写解码器。 然后让我们实现解码器:
public static class MessageDecoder extends MessageToMessageDecoder<ByteBuf>
{@Overrideprotected void decode( ChannelHandlerContext ctx, ByteBuf msg, List<Object> out ) throws Exception{int value = msg.readInt();out.add( new Foo(value) );}
}
现在,如果我们再次运行测试,那就一切顺利了。 现在,我们可以对一些更复杂的结构进行编码/解码,并相应地更新测试。
翻译自: https://www.javacodegeeks.com/2015/06/netty-testing-encodersdecoders.html