天天看點

Netty:測試 Encoder 和 Decoder

最近用了一段時間的Netty,現建構了一個編碼器/解碼器管道,以測試編碼器和解碼器在沒有發送真實的消息時是否在正常工作。

友善的是,Netty 有個 EmbeddedChannel,使測試變得非常輕松。 

假設我們有一條消息“ Foo”,我們想通過網絡發送。它僅包含一個整數值,是以我們将其發送并在另一側重建“ Foo”。 我們可以編寫以下編碼器來執行此操作:

public static class MessageEncoder extends MessageToMessageEncoder<Foo>

{

    @Override

    protected 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()

{

    // given

    EmbeddedChannel channel = new EmbeddedChannel( new MessageEncoder(), new MessageDecoder() );



    // when

    Foo foo = new Foo( 42 );

    channel.writeOutbound( foo );

    channel.writeInbound( channel.readOutbound() );



    // then

    Foo returnedFoo = (Foo) channel.readInbound();

    assertNotNull(returnedFoo);

    assertEquals( foo.value(), returnedFoo.value() );

}



public static class MessageDecoder extends MessageToMessageDecoder<ByteBuf>

{

    @Override

    protected void decode( ChannelHandlerContext ctx, ByteBuf msg, List<Object> out ) throws Exception { }

}
      

在測試中,我們将“ Foo”寫入出站通道,然後将其讀回入站通道,然後檢查我們所獲得的内容。如果我們現在運作該測試,将會看到以下内容:

junit.framework.AssertionFailedError

at NettyTest.shouldEncodeAndDecodeVoteRequest(NettyTest.java:28)
      

我們傳回的消息為空,這是有道理的,因為我們沒有編寫解碼器。然後實作解碼器:

public static class MessageDecoder extends MessageToMessageDecoder<ByteBuf>

{

    @Override

    protected void decode( ChannelHandlerContext ctx, ByteBuf msg, List<Object> out ) throws Exception

    {

        int value = msg.readInt();

        out.add( new Foo(value) );

    }

}
      

現在,如果我們再次運作測試,那一切就變成綠色。現在,我們可以對一些更複雜的結構進行編碼/解碼,并相應地更新測試。

原文位址: https://www.zhblog.net/go/java/tutorial/java-netty-encoder-decoder?t=603