【发布时间】:2014-11-20 05:24:39
【问题描述】:
当方法运行时,我想抛出异常(在测试时)。 我可以做几件事:
- stub(mock.someMethod("some arg")).toThrow(new RuntimeException());
- when(mock.someMethod("some arg")).thenThrow(new RuntimeException())
- 投掷.....
通常我会创建一个 spy 对象来调用 spy 方法。使用存根我可以抛出异常。此异常始终在日志中进行监控。更重要的是测试不会崩溃,因为抛出异常的方法可以捕获它并返回特定的值。但是,在下面的代码中没有抛出异常(日志中没有任何内容被监控 && 返回值为真但应该为假)。
问题:在这种情况下不会抛出异常:
DeviceInfoHolder deviceInfoHolder = new DeviceInfoHolder();
/*Create Dummy*/
DeviceInfoHolder mockDeviceInfoHolder = mock (DeviceInfoHolder.class);
DeviceInfoHolderPopulator deviceInfoHolderPopulator = new DeviceInfoHolderPopulator();
/*Set Dummy */
deviceInfoHolderPopulator.setDeviceInfoHolder(mockDeviceInfoHolder);
/*Create spy */
DeviceInfoHolderPopulator spyDeviceInfoHolderPopulator = spy(deviceInfoHolderPopulator);
/*Just exception*/
IllegalArgumentException toThrow = new IllegalArgumentException();
/*Stubbing here*/
stub(spyDeviceInfoHolderPopulator.populateDeviceInfoHolder()).toThrow(toThrow);
/*!!!!!!Should be thrown an exception but it is not!!!!!!*/
boolean returned = spyDeviceInfoHolderPopulator.populateDeviceInfoHolder();
Log.v(tag,"Returned : "+returned);
【问题讨论】:
-
检查你的方法不是最终的。最终方法不能被存根。
-
您想通过此日志记录实现什么目标?如果您的测试方法抛出异常,只需将其冒泡,测试框架将负责记录
-
如果在方法内部抛出异常,它将返回false。
-
我想测试方法中什么时候会抛出异常的返回。记录只是为了观察
标签: java android testing mockito stubs