TFrameCodec extends ByteToMessageCodec<TFrame> { @Override protected void encode(ChannelHandlerContext ctx, TFrame frame, ByteBuf out) throws Exception { out.writeShort(frame.size + TFrame.FRAME_HEADER_LENGTH); out.writeByte(frame.type); out.writeZero(1); out.writeInt((int) frame.id); out.writeZero(8); out.writeBytes(frame.payload); }  static ByteBuf encode(ByteBufAllocator allocator, TFrame frame); static TFrame decode(ByteBuf buffer);  }
@Test public void encodeWithoutError() { ByteBuf allocatedByteBuf1 = Unpooled.buffer(TFrame.FRAME_SIZE_LENGTH); ByteBufAllocator allocator = Mockito.mock(ByteBufAllocator.class); when(allocator.buffer(TFrame.FRAME_HEADER_LENGTH, TFrame.FRAME_HEADER_LENGTH)).thenReturn(allocatedByteBuf1); String payload = "Hello, World!"; ByteBuf buffer = Unpooled.wrappedBuffer(payload.getBytes(StandardCharsets.UTF_8)); TFrame frame = new TFrame( 10, FrameType.InitRequest, Integer.MAX_VALUE, buffer ); TFrameCodec.encode(allocator, frame); verify(allocator, times(1)).buffer(TFrame.FRAME_HEADER_LENGTH, TFrame.FRAME_HEADER_LENGTH); assertEquals(1, allocatedByteBuf1.refCnt()); }
@Test public void encodeWithError() { ByteBuf allocatedByteBuf1 = Unpooled.buffer(TFrame.FRAME_SIZE_LENGTH); ByteBufAllocator allocator = Mockito.mock(ByteBufAllocator.class); when(allocator.buffer(TFrame.FRAME_HEADER_LENGTH, TFrame.FRAME_HEADER_LENGTH)).thenReturn(allocatedByteBuf1); CompositeByteBuf buffer = Mockito.mock(CompositeByteBuf.class); when(buffer.writerIndex(anyInt())).thenThrow(new RuntimeException("Can't write")); TFrame frame = new TFrame( 10, FrameType.InitRequest, Integer.MAX_VALUE, buffer ); try { TFrameCodec.encode(allocator, frame); fail(); } catch (Exception e) { assertEquals("Can't write", e.getMessage()); } verify(allocator, times(1)).buffer(TFrame.FRAME_HEADER_LENGTH, TFrame.FRAME_HEADER_LENGTH); assertEquals(0, allocatedByteBuf1.refCnt()); }