Reputation: 572
I have a piece of code in my android app that catches one exception and rethrows it as another, custom exception extended from RuntimeException
. And it seems impossible to be tested.
Take a look at the following code:
try { ... } catch (MalformedURLException e) {
throw new CustomMalformedDataException(downloadUrlString, e);
}
When I try to test the exception case, I write:
@Test(expected = CustomMalformedDataException.class)
public void exceptionsTest() throws Exception {
<code triggering the exception>
}
But i get Test running failed: Instrumentation run failed due to 'java.net.MalformedURLException'
When I write:
@Test(expected = MalformedURLException.class)
public void exceptionsTest() throws Exception {
<code triggering the exception>
}
I get java.lang.Exception: Unexpected exception, expected<java.net.MalformedURLException> but was<CustomMalformedDataException>
So how should I test this case?
Code of exception class:
public class CustomMalformedDataException extends RuntimeException {
public CustomMalformedDataException(String message, Throwable cause) {
super(message, cause);
}
public CustomMalformedDataException(String url, MalformedURLException cause) {
super("The package has an invalid \"downloadUrl\": " + url, cause);
}
}
UPDATE: It seems that either way tests stop execution at the point where the initial exception is thrown, even though it is caught. But in case this exception is expected, the execution continues and throws another exception, which is already not expected.
Upvotes: 4
Views: 1582
Reputation: 523
So I tried out your code and got a different error so I can't give you an answer, but I've got a way of testing errors I prefer using JUnit that will get you the results you need
@Rule
public final ExpectedException exception = ExpectedException.none();
@Test
public void testExceptionOccurs() throws Exception {
exception.expect(CustomMalformedDataException.class);
//code that casues exception to happen
}
I've run this plenty of times and it works with no issues when I need to test that my exceptions are occuring. I hope this at least helps giving you a solution to writing exception tests.
If you really need to test RuntimeException
then have your test throw RuntimeException
instead of Exception
Upvotes: 1