我试图写一个单元测试此:如何正确模拟自动关闭的资源?
try (final DatagramChannel channel = helper.createChannel()) {
...
}
在我的测试,我嘲笑助手(使用的Mockito),并告诉helper.createChannel()返回一个嘲笑道。
此测试失败,
java.lang.NullPointerException
at java.nio.channels.spi.AbstractInterruptibleChannel.close(AbstractInterruptibleChannel.java:111)
据我所知,试与 - 资源工厂在Java中在退出try块调用了DatagramChannel的close()方法,但应该不是关闭()方法在模拟的DatagramChannel被调用?
调试器告诉我AbstractInterruptibleChannel中的closeLock为null。
我应该继承DatagramChannel吗?重写close()方法,然后模拟我的子类吗? 或者,我是否以更深刻的方式做了错误的事情(帮手模拟模拟)?
问候, 弗雷德里克Israelsson
测试代码,根据要求:
@Mock
private InetAddress peerAddress;
@Mock
private UDPChannelHelper helper;
@Mock
private DatagramChannel channel;
private UDPTransportImpl transport;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
when(helper.createChannel()).thenReturn(channel);
transport = new UDPTransportImpl(peerAddress, 0, helper);
}
@Test
public void testNormalSubmit() throws Exception {
transport.submit("Hello");
}
正如你所看到的,我不指定任何channel.close行为()。我相信我不应该,因为close()返回void。
你能展示你的代码在哪里嘲笑这些吗?也有你通过调试,并确认a)辅助实际上是一个模拟,b)helper.createChannel()也返回一个模拟对象? – cowls 2013-02-28 08:50:44
添加了测试代码,并且在调试器中,助手和通道的类型都是BlaBlaBla $$ EnhancerByMockitoWithCGLIB。 – 2013-02-28 09:06:55
本页面:http://mockito.googlecode.com/svn/tags/latest/javadoc/org/mockito/Mockito.html#doNothing%28%29明确指出“虚拟模拟方法默认不做任何事情!”。所以我们只能假设finally块不是在模拟上执行的。你的代码对我来说看起来很好,尽管如此我不知道为什么这是..你当然不应该需要自己的子类。 – cowls 2013-02-28 09:34:35