[JUnit] Test the thrown exception

Tests thrown exceptions when writing unit tests in JUnit for Java code. I did some research a long time ago, but when I went to the front end for a while, When I came back, I was asked "How is it?", So I will summarize it as a memorandum.

Verification environment

JUnit: 4.12

Method

The following two are described.

  1. Specify the exception class to be thrown using the @Test option ʻexpected`
  2. Specify ʻExpectedException in @Rule` and specify the exception to be thrown in the test method.

Specify the exception class to be thrown using the @ Test option ʻexpected`

It's simple, but it only validates the exception class that is thrown. The code sample is as follows.

@Test(expected = IllegalArgumentException.class)
public void createAccountUserNameIsEmpty() {
    // followings are test-code should throw IllegalArgumentException
    // ...
}

It is written in the code of option ʻexpected, but in order to verify the message etc. Let's use ʻExpectedException described later. You can also validate Caused by exceptions. The following article describes the validation of Caused by exceptions. https://qiita.com/komiya_atsushi/items/082d6a71e475a613338a

Specify ʻExpectedException in @ Rule` and specify the exception to be thrown in the test method.

As I mentioned a bit earlier, you can validate exception messages as well as throwed exception classes. The code sample is as follows.

//Be sure to make it public rather than usage
//Because the constructor is private, you can't just do new.none()Create an object by
// none()Means that the test target does not always throw an exception
@Rule
public ExpectedException expectedException = ExpectedException.none();

@Test
public void createAccountUserNameIsEmpty() {
    //Exception class validation
    expectedException.expect(IllegalArgumentException.class);
    //Exception message validation
    expectedException.expectMessage("Failed to create an account; user name is empty.");
    // followings are test-code should throw IllegalArgumentException
    // ...
}

I'm curious, but I haven't checked

It's also the laziness of not reading the code description properly ...

Recommended Posts

[JUnit] Test the thrown exception
Try JUnit test launch
Unit test with Junit.
Get the name of the test case in the JUnit test class
Test the contents of an Excel file with JUnit
[Java] JUnit4 test case example
[Spring] Controller exception output test
Test private methods in JUnit
Test private methods in JUnit
Check the behavior when the exception specified by expected in JUnit 4 @Test annotation occurs / does not occur
[Spring Boot] Until @Autowired is run in the test class [JUnit5]
JUnit 5 parameterization test is super convenient
Output JUnit test report in Maven
[Java] Test private methods with JUnit
What are the rules in JUnit?
Test Spring framework controller with Junit