When the method is running I would like to throw an exception (while testing). I could do few things:
- stub(mock.someMethod("some arg")).toThrow(new RuntimeException());
- when(mock.someMethod("some arg")).thenThrow(new RuntimeException())
- doThrow.....
Usually I create a spy object to call spied method. Using stubbing I can throw an exception. This exception is always monitored in log. More importantly is that the test does not crash because the method where the exception was thrown could catch it and return specific value. However, in the code bellow exception is not thrown (nothing is monitored in the log && return value is true but should be false).
Issues: In this case the exception is not thrown:
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);
Creating new answer, because spyDeviceInfoHolderPopulator.populateDeviceInfoHolder(); is your testing method.
One of the basic rules of unit testing is that your shouldn't stub on testing method, because you want to test it's behavior. You may want to stub methods of faked dependencies of test class with Mockito.
So in this case, you probably want to remove the spy, call your testing method and as last stage of your test (that is missing currently), you should verify if logic in testing method was correct.
EDIT:
After last comment it is finally clear to me what logic you are testing. Let say that your testing object has dependency on some XmlReader. Also immagine that this reader has method called "readXml()" and is used in your testing logic for reading from XML. My test would look like this:
XmlReader xmlReader = mock (XmlReader.class);
mock(xmlReader.readXml()).doThrow(new IllegalArgumentException());
DeviceInfoHolderPopulator deviceInfoHolderPopulator = new DeviceInfoHolderPopulator(xmlReader);
//call testing method
boolean returned = spyDeviceInfoHolderPopulator.populateDeviceInfoHolder();
Assign.assignFalse(returned);