(Test Lifecycle) (Sample Unit Test)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 1

@Author("Adrian Więch")

{ JUnit 5 CHEAT SHEET }

{ SAMPLE UNIT TEST } { TEST LIFECYCLE }


@Test
void should_RetTrue_When_DietRecom() {
@BeforeAll
// given
double wght = 90.0;
double hght = 1.92;
@BeforeEach
// when
boolean recommended =
BMICalc.isDietRecommended(wght, hght); @Test
// then
assertTrue(recommended);
} @AfterEach

{ TEST TYPES }
@AfterAll
// basic test
@Test
// repeat test 10x
@RepeatedTest(10) { ASSERTION TYPES }
// parameterize single value
@ParameterizedTest // check if x is true/false
@ValuesSource(doubles = {70.0, 80.0}) assertTrue(x);
void testName(Double param) { … } assertFalse(x);

// parameterize multiple values // check if object is null


@ParameterizedTest(name = "w={0}, h={1}") assertNull(object);
@CsvSource(value = {
"70.0, 1.82", "80.0, 1.72" // check if expected equals actual
}) // (primitive types only)
void testName(Double par1, Double par2) assertEquals(expected, actual);

// params from csv file, ignore header // check if array1 and array2
@ParameterizedTest // contain the same elements
@CsvFileSource( assertArrayEquals(array1, array2);
resources = "/diet-params.csv",
numLinesToSkip = 1 // check if doSth() throws
) // SampleExeception
void testName(Double par1, Double par2) Executable executable = () -> doSth();
assertThrows(
SampleException.class,
{ OTHER } executable
);
// nested class
@Nested // check multiple assertions
class InnerClass { … } assertAll(
() → assertEquals(expected1, actual1),
// display name () → assertEquals(expected2, actual2)
@DisplayName("Custom name") );

// skip test // set maximal execution time


@Disabled Executable executable = () -> doSth();
assertTimeout(
// skip test under condition Duration.ofMillis(500),
assumeTrue(env.equals("prod")) executable
);

You might also like