Here`s how to check if an exception occurs when running a test.
Method using Annotation
Annotation can be used to test whether an exception has occurred.
You can specify the expected exception when executing the code like @Test(expected = Exception)
.
In the code below, the test will pass if a NullPointerException is thrown, otherwise it will fail.
@Test(expected = NullPointerException.class)
public void testExceptionThrown() {
String str = null;
str.contains("a");
}
Method using ExpectedException Rule
You can test whether an Exception occurs using a Rule called ExpectedException.
If the test below throws a NullPointerException, the test will pass. You can specify the exception that you expect to occur in the expect()
method.
@Rule
public ExpectedException exceptionRule = ExpectedException.none();
@Test
public void testExceptionThrown() {
exceptionRule.expect(NullPointerException.class);
String str = null;
str.contains("a");
}
Check the message contents of the Exception
If the code above throws a NullPointerException, the test will pass, but sometimes its hard to guarantee that the code I
m expecting throws an Exception.
In this case, you can test more accurately by checking the contents of the message of the exception.
In the code below, the test only passes when the message of NullPointerException is "Null object is invoked"
.
@Rule
public ExpectedException exceptionRule = ExpectedException.none();
@Test
public void testExceptionThrown2() {
exceptionRule.expect(NullPointerException.class);
exceptionRule.expectMessage("Null object is invoked");
throw new NullPointerException("Null object is invoked");
}
If a NullPointerException of another message occurs as shown below, the test fails.
@Test
public void testExceptionThrown2() {
exceptionRule.expect(NullPointerException.class);
exceptionRule.expectMessage("Null object is invoked");
throw new NullPointerException("Null object");
}
The failure message will look something like this:
java.lang.AssertionError:
Expected: (an instance of java.lang.NullPointerException and exception with message a string containing "Null object is invoked")
but: exception with message a string containing "Null object is invoked" message was "Null object"
How to use try-catch
You can test whether an exception is raised using try-catch as shown below. When an exception occurs, it goes to catch, so fail()
is not called and the test passes.
If no exception occurs, fail()
is called and the test fails.
@Test
public void testExceptionThrown3() {
try {
String str = null;
str.contains("a");
fail();
} catch (NullPointerException e) {
// pass
}
}
Related Posts
- Java - Remove items from List while iterating
- Java - How to find key by value in HashMap
- Java - Update the value of a key in HashMap
- Java - How to put quotes in a string
- Java - How to put a comma (,) after every 3 digits
- BiConsumer example in Java 8
- Java 8 - Consumer example
- Java 8 - BinaryOperator example
- Java 8 - BiPredicate Example
- Java 8 - Predicate example
- Java 8 - Convert Stream to List
- Java 8 - BiFunction example
- Java 8 - Function example
- Java - Convert List to Map
- Exception testing in JUnit
- Hamcrest Collections Matcher
- Hamcrest equalTo () Matcher
- AAA pattern of unit test (Arrange/Act/Assert)
- Hamcrest Text Matcher
- Hamcrest Custom Matcher
- Why Junit uses Hamcrest
- Java - ForkJoinPool
- Java - How to use Futures
- Java - Simple HashTable implementation
- Java - Create a file in a specific path
- Java - Mockito의 @Mock, @Spy, @Captor, @InjectMocks
- Java - How to write test code using Mockito
- Java - Synchronized block
- Java - How to decompile a ".class" file into a Java file (jd-cli decompiler)
- Java - How to generate a random number
- Java - Calculate powers, Math.pow()
- Java - Calculate the square root, Math.sqrt()
- Java - How to compare String (==, equals, compare)
- Java - Calculate String Length
- Java - case conversion & comparison insensitive (toUpperCase, toLowerCase, equalsIgnoreCase)