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.
JUnit: 4.12
The following two are described.
@Test
option ʻexpected` in
@Rule` and specify the exception to be thrown in the test method.@ 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
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
// ...
}
It's also the laziness of not reading the code description properly ...
@Rule
? I feel that if you master @Rule
, you can write tests more efficiently. is an implementation class of
TestRule, but who is
TestRule`?Recommended Posts