当方法运行时,我想抛出异常(在测试时)。我可以做几件事:
- 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);