我正在使用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
是否支持channelActive
或channelRegister
?
答案 0 :(得分:2)
EmbeddedChannel在构造之后处于活动状态,因此添加的处理程序添加得太晚。通过构造函数添加它们,它应该工作:
EmbeddedChannel channel = new EmbeddedChannel(
new LoggingHandler(LogLevel.TRACE),
new ClientEventHandler(currentMessage));