gpt4 book ai didi

java - Netty单元测试: How to test invocations on the Channel object that is part of the passed ChannelHandlerContext?

转载 作者:行者123 更新时间:2023-12-02 08:59:36 24 4
gpt4 key购买 nike

ChannelHandler 实现的部分行为是它应该在收到消息后发送响应。但是,传递的 ChannelHandlerContext 似乎确实创建了一个内部 Channel 实例,该实例与单元测试中使用的 EmbeddedChannel 实例不同。因此,无法从外部测试响应是否已实际写入 channel 。

这里是一些代码来澄清问题:

public class EchoHandler extends SimpleChannelInboundHandler<Object>
{
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception
{
ctx.channel().writeAndFlush(msg);
}
}

@Test
public void aTest() throws Exception
{
EchoHandler handler = new EchoHandler();
EmbeddedChannel channel = spy(new EmbeddedChannel(handler));
Object anObject = new Object();
channel.writeInbound(anObject);
verify(channel, times(1)).writeAndFlush(eq(anObject)); // will fail
}

最佳答案

就这么简单:

public class EchoHandlerTest {

static class EchoHandler extends ChannelInboundHandlerAdapter {

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ctx.channel().writeAndFlush(msg);
}
}

@Test
public void aTest() throws Exception {
EmbeddedChannel channel = new EmbeddedChannel(new EchoHandler());
Object anObject = new Object();
channel.writeInbound(anObject);
assertThat(channel.readOutbound(), is(anObject));
}
}

关于java - Netty单元测试: How to test invocations on the Channel object that is part of the passed ChannelHandlerContext?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60259809/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com