Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito How to mock and assert a thrown exception?

People also ask

How do you assert an exception is thrown JUnit?

When using JUnit 4, we can simply use the expected attribute of the @Test annotation to declare that we expect an exception to be thrown anywhere in the annotated test method. In this example, we've declared that we're expecting our test code to result in a NullPointerException.

How do you assert exception not thrown?

If you want to test a scenario in which an exception should be thrown then you should use the expected annotation. If you want to test a scenario where your code fails and you want to see if the error is correctly handled: use expected and perhaps use asserts to determine if it's been resolved.

How do you throw an exception in a test case?

In order to test the exception thrown by any method in JUnit 4, you need to use @Test(expected=IllegalArgumentException. class) annotation. You can replace IllegalArgumentException. class with any other exception e.g. NullPointerException.


To answer your second question first. If you're using JUnit 4, you can annotate your test with

@Test(expected=MyException.class)

to assert that an exception has occured. And to "mock" an exception with mockito, use

when(myMock.doSomething()).thenThrow(new MyException());

BDD Style Solution (Updated to Java 8)

Mockito alone is not the best solution for handling exceptions, use Mockito with Catch-Exception

Mockito + Catch-Exception + AssertJ

given(otherServiceMock.bar()).willThrow(new MyException());

when(() -> myService.foo());

then(caughtException()).isInstanceOf(MyException.class);

Sample code

  • Mockito + Catch-Exception + Assertj full sample

Dependencies

  • eu.codearte.catch-exception:catch-exception:2.0
  • org.assertj:assertj-core:3.12.2

If you want to test the exception message as well you can use JUnit's ExpectedException with Mockito:

@Rule
public ExpectedException expectedException = ExpectedException.none();

@Test
public void testExceptionMessage() throws Exception {
    expectedException.expect(AnyException.class);
    expectedException.expectMessage("The expected message");

    given(foo.bar()).willThrow(new AnyException("The expected message"));
}

Updated answer for 06/19/2015 (if you're using java 8)

Just use assertj

Using assertj-core-3.0.0 + Java 8 Lambdas

@Test
public void shouldThrowIllegalArgumentExceptionWhenPassingBadArg() {
assertThatThrownBy(() -> myService.sumTingWong("badArg"))
                                  .isInstanceOf(IllegalArgumentException.class);
}

Reference: http://blog.codeleak.pl/2015/04/junit-testing-exceptions-with-java-8.html


If you're using JUnit 4, and Mockito 1.10.x Annotate your test method with:

@Test(expected = AnyException.class)

and to throw your desired exception use:

Mockito.doThrow(new AnyException()).when(obj).callAnyMethod();