JUnit test abnormalities
- Ancient writing
@Test
void name() {
boolean hasException = false;
String exceptionMessage = null;
try {
check();
} catch (RuntimeException e) {
hasException = true;
exceptionMessage = e.getMessage();
}
assertEquals("runtime", exceptionMessage);
assertTrue(hasException);
}
void check() {
throw new RuntimeException("runtime");
}
- Longhand (fallible)
the Check and the Message exception type
@Test
void name() {
assertThrows(RuntimeException.class, () -> check(), "aaa");
}
void check() {
throw new RuntimeException("runtime");
}
This test we found that abnormal test message but not able to live.
Pa Pa a source
Found that consumption actually test message is not unusual news, but the exception is not expected, and there is no fault to consumption.
2.1 longhand
@Test
void name() {
final RuntimeException runtimeException = assertThrows(RuntimeException.class, () -> check());
assertEquals("runtime", runtimeException.getMessage());
}
void check() {
throw new RuntimeException("runtime");
}
3. Streaming writing
@Test
void name() {
assertThatThrownBy(() -> check())
.isInstanceOf(RuntimeException.class)
.hasMessage("runtime");
}
void check() {
throw new RuntimeException("runtime");
}
Personally I think the wording of the current flow within the purview of the most elegant.