How to Assert That a Certain Exception Is Thrown in Junit Tests

How do you assert that a certain exception is thrown in JUnit tests?

It depends on the JUnit version and what assert libraries you use.

  • For JUnit5 and 4.13 see answer https://stackoverflow.com/a/2935935/2986984
  • If you use assertJ or google-truth, see answer https://stackoverflow.com/a/41019785/2986984

The original answer for JUnit <= 4.12 was:

@Test(expected = IndexOutOfBoundsException.class)
public void testIndexOutOfBoundsException() {

ArrayList emptyList = new ArrayList();
Object o = emptyList.get(0);

}

Though answer https://stackoverflow.com/a/31826781/2986984 has more options for JUnit <= 4.12.

Reference :

  • JUnit Test-FAQ

JUnit 5: How to assert an exception is thrown?

You can use assertThrows(), which allows you to test multiple exceptions within the same test. With support for lambdas in Java 8, this is the canonical way to test for exceptions in JUnit.

Per the JUnit docs:

import static org.junit.jupiter.api.Assertions.assertThrows;

@Test
void exceptionTesting() {
MyException thrown = assertThrows(
MyException.class,
() -> myObject.doThing(),
"Expected doThing() to throw, but it didn't"
);

assertTrue(thrown.getMessage().contains("Stuff"));
}

How do I assert my exception message with JUnit Test annotation?

You could use the @Rule annotation with ExpectedException, like this:

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

@Test
public void shouldThrowRuntimeExceptionWhenEmployeeIDisNull() throws Exception {
expectedEx.expect(RuntimeException.class);
expectedEx.expectMessage("Employee ID is null");

// do something that should throw the exception...
System.out.println("=======Starting Exception process=======");
throw new NullPointerException("Employee ID is null");
}

Note that the example in the ExpectedException docs is (currently) wrong - there's no public constructor, so you have to use ExpectedException.none().

How do I use Assert to verify that an exception has been thrown?

For "Visual Studio Team Test" it appears you apply the ExpectedException attribute to the test's method.

Sample from the documentation here: A Unit Testing Walkthrough with Visual Studio Team Test

[TestMethod]
[ExpectedException(typeof(ArgumentException),
"A userId of null was inappropriately allowed.")]
public void NullUserIdInConstructor()
{
LogonInfo logonInfo = new LogonInfo(null, "P@ss0word");
}

Mockito How to mock and assert a thrown exception?

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

How to test for the exception in junit

I don't know if it's available in all versions of JUnit (I use junit 4.12). What I usely do is to add the expected exception after the Test annotation, for example:

@Test(expected = MySpecificException.class)

There are other ways to do, but that's a possibility. You can create a specific MySpecificException class (which extends Exception class), and you throw this specific exception in your code. Then you can check that it is thrown correctly with junit.

Have fun !

JUnit Testing Exceptions

@Test(expected = Exception.class)  

Tells Junit that exception is the expected result so test will be passed (marked as green) when exception is thrown.

For

@Test

Junit will consider test as failed if exception is thrown, provided it's an unchecked exception. If the exception is checked it won't compile and you will need to use other methods.
This link might help.

Test if an exception is caught with Junit

You won't catch exceptions that are not thrown. Just test the 'throwing exception' method instead of the 'exception catching' one

@Test(expected = InvalidParameterExeption.class)
public void testIfFaultyDataPacketIsRecognised() {
analyseData(faultyDataPacket);
}


Related Topics



Leave a reply



Submit