Java junit 5
From wikinotes
Documentation
official docs https://junit.org/junit5/docs/current/user-guide/ javadocs https://junit.org/junit5/docs/current/api/ homepage https://junit.org/junit5/
Usage
JUnit has a standalone console runner that can be used. If you are already using a build system, I recommend using that to run your tests.
java maven plugin: junit
Configuration
stdout/stderr
By default, stdout/stderr is not printed in output. You can enable output, but unlike python it is printed for both passing/failing tests.
<plugin...> <configuration> <junit.platform.output.capture.stdout>true</junit.platform.output.capture.stdout> <junit.platform.output.capture.stderr>true</junit.platform.output.capture.stderr> </configuration> </plugin...>
Syntax
Simple Example
import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class TestApp { @Test void four_plus_four_is_eight() { int sum = 4 + 4; Assertions.assertEquals(sum, 8); } }I like to map out methods in nested classes.
import org.junit.jupiter.Test; import org.junit.jupiter.Assertions; import org.junit.jupiter.Nested; class TestPrinter { @Nested // <-- allows nested class to be visible to junit class Test_print { @Test void test_blankpage() { Printer printer = new Printer(); String result = printer.print(); String expects = ""; Assertions.assertEquals(expects, result); } } }Assertions
Assertions.fail("reason"); Assertions.assertEquals(x, y); Assertions.assertSame(x, y); Assertions.assertTrue(x, y);Annotations
Annotations are used to indicate tests, setup/teardown methods etc.
Setup/Teardown
This list is not complete, see docs.
import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.AfterEach; class TestClass { @BeforeAll public void setup_module() {}; @AfterAll public void teardown_module() {}; @BeforeEach public void setup_method() {}; @AfterEach public void teardown_method() {}; }Parametrized Tests
import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; class TestMyClass { String[] alphabet = {"a", "b", "c", "d", "e", ...}; @ParameterizedTest @ValueSource(strings = {"a", "b", "c"}) void test_is_letter(String ch) { Assertions.assert(ch in alphabet); } }
Troubleshooting
maven/eclipse cannot find tests
- Ensure tests are under
${project}/src/test/../Test*.java
- Ensure test-class matches filename