How can I use Junit4 to test the thrown exception while using the exception mapper ?
To test a thrown exception, expected from the execution. Please use :
#Test(expected=<ExpectedException>.class)
public void testThrownException() {
// Your test code that throws the expected exception
}
The test would pass if your code throws the expected exception and fail for assertion failures and any other exception thrown by the code.
Related
In the following test code, I make a declaration: when the get() method is called with argument 0, then an exception should be thrown out. In my opinion, if the argument is not 0, the exception should not be thrown out. But, the test was passed. That means get(1) has caused an exception was thrown. Is this a bug of Mockito?
#RunWith(MockitoJUnitRunner.class)
public class MockitoTest {
#Mock
private List<Integer> mockedList;
#Test(expected = Exception.class)
public void test() throws Exception {
when(mockedList.get(0)).thenThrow(new Exception());
mockedList.get(1);
}
}
You set up your test incorrectly and misinterpreted the outcome of your test.
The problem lies in the line:
when(mockedList.get(0)).thenThrow(new Exception());
The signature of "get" method does not allow checked excetions.
Thus, when you pass a checked exception to thenThrow, Mockito rightfully reports it with:
org.mockito.exceptions.base.MockitoException:
Checked exception is invalid for this method!
Invalid: java.lang.Exception
Thus the exception reported is MockitoException, not the Exception you passed to thenThrow. It is thrown even if you omit a call to mockedList.get(1);
To fix, use a RuntimeException, preferrably one that can be reported by get.
when(mockedList.get(0)).thenThrow(new IndexOutOfBoundsException());
Note that you stub a call that is not made afterwards, you need to use a lenient mock with #Mock(lenient = true), otherwise Mockito will report a org.mockito.exceptions.misusing.UnnecessaryStubbingException
How do I test if an assertion is thrown by the method under test using junit? Heres the method I'm testing:
public int f(int i){
assert i > 0;
return i;
}
I'm using junit 4.12.
You can test it by providing parameter in #Test annotation:
#Test(expected = AssertionError.class)
public void shouldThrowExceptionWhenIncorrectInput() {
f(-3);
}
This will check if the AssertException is thrown.
However, if you want to ensure that this function wont be run with incorrect parameters, you have to be aware that assertions can be turned off by running java with -da parameters.
To ensure that exception is thrown I would suggest throwing IllegalArgumentException inside some validation method, and to provide it with proper message. Then you will be sure that this will always throw exception when incorrect parameters are provided.
I have a method that throws exception. And i have a test like this.
#Rule
public ExpectedException expectedEx = ExpectedException.none();
#Test
public void shouldThrowExceptionIfValidationFails() throws Exception {
doThrow(new InvalidException("Invalid Token")).when(obj).foo(any());
expectedEx.expect(InvalidException.class);
expectedEx.expectMessage("Invalid Token");
// my method call
// verify DB save doesn't happens
assertTrue(false);
}
The test assert for exception, and since the exception is thrown the test passes. It doesn't care about the last line assertTrue(false)
How can i make sure that my other assertions are also satisfied.
This is the pattern I follow for this case. It uses ExpectedException as designed. I like the throw e rather than failing after method method call in the try because it will not result in a false-positive if someone decides to delete the fail (which people have a tendency to do when they see fail() or if a test is failing because it hits a fail()).
#Test
public void shouldThrowExceptionIfValidationFails() throws Exception {
doThrow(new InvalidException("Invalid Token")).when(obj).foo(any());
expectedEx.expect(InvalidException.class);
expectedEx.expectMessage("Invalid Token");
try{
// my method call
}catch(InvalidException e){
// verify DB save doesn't happens
assertTrue(false);
throw e;
}
}
I've written an ExceptionMapper in order to catch all http exception (400,404,500,...) in my application.
#Provider
public class MyExceptionHandler implements ExceptionMapper<Exception> {
#Override
public Response toResponse(Exception ex) {
//Some Code to build Response
}
unfortunately when I send a post request with Content-Type:application/json with empty or wrong format body, this error occurs and I can not catch it in MyExceptionHandler.
Status Code: 400 Bad Request
No content to map due to end-of-input
at [Source: org.apache.catalina.connector.CoyoteInputStream#5774bb5e; line: 1, column: 1]
what did I do wrong?
Thanks a lot.
Environment: JAX-RS, GlassFish 3
Edit:
I think this error is related to AppServer and must be handled there.
When there is a bad request such as wrong format body, the WebApplicationException is thrown. Here is how exception mappers are selected
When a WebApplicationException, or one of its subclasses, with an
empty entity body is thrown, the runtime will check to see if there
is an exception mapper that handles WebApplicationException
exceptions. If there is the exception mapper is used to create the
response sent to the consumer.
When any exception other than a WebApplicationException exception, or
one of its subclasses, is thrown, the runtime will check for an
appropriate exception mapper. An exception mapper is selected if it
handles the specific exception thrown. If there is not an exception
mapper for the specific exception that was thrown, the exception
mapper for the nearest superclass of the exception is selected.
Here is what I would recommend
register an ExceptionMapper<WebApplicationException>
register an ExceptionMapper<Throwable> to catch all other exceptions with a generic response signaling a 500 sever error.
I'm using ScalaTest for testing some Scala code.
I currently testing for expected exceptions with code like this
import org.scalatest._
import org.scalatest.matchers.ShouldMatchers
class ImageComparisonTest extends FeatureSpec with ShouldMatchers{
feature("A test can throw an exception") {
scenario("when an exception is throw this is expected"){
evaluating { throw new Exception("message") } should produce [Exception]
}
}
}
But I would like to add additional check on the exception, e.g. I would like to check that the exceptions message contains a certain String.
Is there a 'clean' way to do this? Or do I have to use a try catch block?
I found a solution
val exception = intercept[SomeException]{ ... code that throws SomeException ... }
// you can add more assertions based on exception here
You can do the same sort of thing with the evaluating ... should produce syntax, because like intercept, it returns the caught exception:
val exception =
evaluating { throw new Exception("message") } should produce [Exception]
Then inspect the exception.
If you need to further inspect an expected exception, you can capture it using this syntax:
val thrown = the [SomeException] thrownBy { /* Code that throws SomeException */ }
This expression returns the caught exception so that you can inspect it further:
thrown.getMessage should equal ("Some message")
you can also capture and inspect an expected exception in one statement, like this:
the [SomeException] thrownBy {
// Code that throws SomeException
} should have message "Some message"