EmbeddedChannel和channelActive

时间:2016-11-04 12:05:49

标签: java netty

我正在使用EmbeddedChannel为我的应用程序编写单元测试:

@Test
public void sendMessage() {
    CurrentMessage currentMessage = new CurrentMessage();
    currentMessage.setCommand(CommandEnum.CURRENT_MEASUREMENT_REQUEST);

    EmbeddedChannel channel = new EmbeddedChannel();
    channel.pipeline().addLast(new LoggingHandler(LogLevel.TRACE));
    channel.pipeline().addLast(new ClientEventHandler(currentMessage));
    assertTrue(channel.isActive());
}

但我的channelActive ClientEventHandler未被调用:

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    IConverter converter = CommandUtil.commands.get(message.getCommand().getHexValue());

    byte[] byteMessage = converter.encode(message);

    logger.info("Sending byte array message: " + byteMessage);

    ctx.writeAndFlush(Unpooled.copiedBuffer(byteMessage));
}

EmbeddedChannel是否支持channelActivechannelRegister

1 个答案:

答案 0 :(得分:2)

EmbeddedChannel在构造之后处于活动状态,因此添加的处理程序添加得太晚。通过构造函数添加它们,它应该工作:

EmbeddedChannel channel = new EmbeddedChannel(
        new LoggingHandler(LogLevel.TRACE),
        new ClientEventHandler(currentMessage));