EmbeddedChannel 和 channelActive

EmbeddedChannel and channelActive

我正在使用 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());
}

但是 ClientEventHandler 中的 channelActive 没有被调用:

@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

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

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