org.junit.jupiter.api @Test(expected = Exception.class)
public void throwsExceptionTest() {
// ...
} @Test
public void throwsExceptionTest() {
assertThrows(Exception.class, () -> {
//...
});
} @Test(timeout = 5)
public void failWithTimeoutTest() {
service.process(request);
} @Test
public void failWithTimeoutTest() {
assertTimeout(Duration.ofMillis(5), () ->
service.process(request));
} org.junit.jupiter.api.Assertions // JUnit 4
assertEquals(«my message», 1, 2);
// JUnit 5
assertEquals(1, 2, «my message»); org.junit.jupiter.api.Assumptions @Test
public void nothingInParticularTest() {
assumeThat("foo", is("bar"));
assertEquals(...);
} @Test
public void nothingInParticularTest() {
assumingThat("foo".equals("bar"), () -> {
assertEquals(...);
});
} @RunWith(SpringJUnit4ClassRunner.class)
class MyControllerTest {
// ...
} @ExtendWith(SpringExtension.class)
class MyControllerTest {
// ...
} @RegisterExtension
static MyExtension extension = new MyExtension(); @DisplayName("Test MyClass")
class MyClassTest {
@Test
@DisplayName("Verify MyClass.myMethod() returns true")
public void myMethodTest() {
// ...
}
} @DisplayName("Verify MyClass")
class MyClassTest {
MyClass underTest;
@Test
@DisplayName("can be instantiated")
public void constructorTest() {
new MyClass();
}
@Nested
@DisplayName("with initialization")
class WithInitialization {
@BeforeEach
public void setup() {
underTest = new MyClass();
underTest.init("foo");
}
@Test
@DisplayName("myMethod returns true")
public void myMethodTest() {
assertTrue(underTest.myMethod());
}
}
} @ParameterizedTest
@ValueSource(strings = {"foo", "bar"})
@NullAndEmptySource
public void myParameterizedTest(String arg) {
underTest.performAction(arg);
}