[英]Netty, how to mock ChannelFuture/ChannelPromise?
I am using Netty 4.0 to create a distributed privacy preserving algorithm for my masters thesis. 我正在使用Netty 4.0为我的硕士学位论文创建分布式隐私保护算法。 I do TDD and most of the time this works very well because of Netty 's modular API.
我使用TDD,由于Netty的模块化API,大多数情况下,此方法效果很好。 One problem I get stuck on last week is I do not know how to test code that depends on
ChannelFutureListener
. 我上周遇到的一个问题是我不知道如何测试依赖
ChannelFutureListener
代码。 So lets say I have following code in my application: 因此,可以说我的应用程序中包含以下代码:
public ChannelFuture close() {
if(channel == null)
throw new IllegalStateException("Channel is null.");
ChannelFuture f = channel.close();
f.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture chf) throws Exception {
channel = null;
}
});
return f;
}
Now I am trying to test this specific method with unit tests. 现在,我正在尝试使用单元测试来测试此特定方法。 For that to work, I need a way to mock out the
ChannelFuture
(ChannelPromise) to control the call of operationComplete
method of the listener. 为此,我需要一种模拟
ChannelFuture
(ChannelPromise)的方法来控制侦听器的operationComplete
方法的调用。 I tried it with different approaches. 我尝试了不同的方法。 Here is one example test case:
这是一个示例测试用例:
@Test
public void testConnectAfterClose() {
Channel chMock = mock(Channel.class);
ChannelPromise promise = new DefaultChannelPromise(chMock);
when(chMock.close()).thenReturn(promise);
node.connect(address);
node.close();
promise.setSuccess();
node.connect(address);
}
This test results in a NullPointerException
at DefaultPromise.notifyListeners()
. 此测试在
DefaultPromise.notifyListeners()
处导致NullPointerException
。 Therefore my question is, how could I test code that depends on ChannelFutureListener
s? 因此,我的问题是,如何测试依赖
ChannelFutureListener
的代码?
I found out a way to solve my problem. 我找到了解决问题的方法。 It works if the mock of the channel (
chMock
) is replaced with a real channel, for example EmbeddedChannel
. 如果将通道的模拟(
chMock
)替换为真实的通道(例如EmbeddedChannel
),则它可以工作。 After that I use a spy
for the channel instead of the mock. 之后,我将
spy
用作通道而不是模拟对象。
Here is my current solution: 这是我当前的解决方案:
@Test
public void testConnectAfterClose() {
Channel helper = new EmbeddedChannel(mock(ChannelHandler.class));
chMock = spy(helper);
when(chMock.close()).thenReturn(promise);
node.connect(address);
node.close();
promise.setSuccess();
node.connect(address);
}
@Morfic: Thank you for your comment. @Morfic:谢谢您的评论。 It was a nice hint for my current solution.
这是我当前解决方案的一个很好的提示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.