Test Classes and Methods
Test methods and lifecycle methods may be declared locally within the current test class,
inherited from superclasses, or inherited from interfaces (see
Test Interfaces and Default Methods). In addition, test methods and
lifecycle methods must not be abstract and must not return a value (except @TestFactory
methods which are required to return a value).
|
Class and method visibility
Test classes, test methods, and lifecycle methods are not required to be It is generally recommended to omit the |
|
Field and method inheritance
Fields in test classes are inherited. For example, a Test methods and lifecycle methods are inherited unless they are overridden according to
the visibility rules of the Java language. For example, a See also: Field and Method Search Semantics |
The following test class demonstrates the use of @Test methods and all supported
lifecycle methods. For further information on runtime semantics, see
Test Execution Order and
Wrapping Behavior of Callbacks.
import static org.junit.jupiter.api.Assertions.fail;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
class StandardTests {
@BeforeAll
static void initAll() {
}
@BeforeEach
void init() {
}
@Test
void succeedingTest() {
}
@Test
void failingTest() {
fail("a failing test");
}
@Test
@Disabled("for demonstration purposes")
void skippedTest() {
// not executed
}
@Test
void abortedTest() {
assumeTrue("abc".contains("Z"));
fail("test should have been aborted");
}
@AfterEach
void tearDown() {
}
@AfterAll
static void tearDownAll() {
}
}
It is also possible to use Java record classes as test classes as illustrated by the
following example.
import static org.junit.jupiter.api.Assertions.assertEquals;
import example.util.Calculator;
import org.junit.jupiter.api.Test;
record MyFirstJUnitJupiterRecordTests() {
@Test
void addition() {
assertEquals(2, new Calculator().add(1, 1));
}
}
Test and lifecycle methods may be written in Kotlin and may optionally use the suspend
keyword for testing code using coroutines.
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
@Suppress("JUnitMalformedDeclaration")
class KotlinCoroutinesDemo {
@BeforeEach
fun regularSetUp() {
}
@BeforeEach
suspend fun coroutineSetUp() {
}
@Test
fun regularTest() {
}
@Test
suspend fun coroutineTest() {
}
}
Using suspending functions as test or lifecycle methods requires
kotlin-stdlib,
kotlin-reflect,
and
kotlinx-coroutines-core
to be present on the classpath or module path.
|