I'm using Mockito
in my unit testing. I have a method
public Status getResponse(Request requset) throws DataException{
}
DataException
is my own defined one which inherited from Exception class.
In my test case
static{
when(process.getResponse(any(Request.class))).
thenReturn(new Status("Success"));
}
It gives an error, Unhandled Exception:DataException
Is there any way in Mockito
to handle this issue without adding try/catch ?
If you want to ignore a test method, use @Ignore along with @Test annotation. If you want to ignore all the tests of class, use @Ignore annotation at the class level.
To specify that the framework throws an exception when a mock object method is invoked or when a mock object property is set or accessed, use the ThrowException class. You can use this action to inject error conditions into the system under test.
In JUnit 5, to write the test code that is expected to throw an exception, we should use Assertions. assertThrows(). In the given test, the test code is expected to throw an exception of type ApplicationException or its subtype. Note that in JUnit 4, we needed to use @Test(expected = NullPointerException.
Don't use a static
block. Use a method tagged with @Before
instead, and tack throws Exception
onto its declaration.
add this to your test method:
@Test(expected=DataException.class)
or use this :
then(caughtException()).isInstanceOf(DataException.class);
for a static-block there is no way other than try-catch.
Another way is to change DataException
to a RuntimeException
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With