净值:测试编码器/解码器
生活随笔
收集整理的這篇文章主要介紹了
净值:测试编码器/解码器
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
我最近與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
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的净值:测试编码器/解码器的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 处处细留心的前一句是什么 处处细留心的前
- 下一篇: 芝士和奶酪一样吗 芝士和奶酪是不是一样的