Saturday, July 12, 2014

How to mock a non-declared checked exception with Mockito

Little useful mocking hack, which costed me quite some time to find:

to throw checked exception from Scala method (which usually don't declare exceptions, which disappoints frameworks like Mockito), use answer:

mockedObject.doSomething(any[Whatever]).answers{ _ => throw new CheckedException("ouch!") } 

where CheckedException is not an instance of RuntimeException. Not because RuntimeException cannot be thrown that way (it can), but because there is a simpler method for those:

mockedObject.doSomething(any[Whatever]) throws new RuntimeException("ouch!")

So if you need to throw e.g. SQLException, method 1 will work, whereas method 2 will compile but complain during the test that such type of exception does not correspond to the signature. For something like ArithmeticException, both methods will work.

No comments:

Post a Comment