maven test class code example
Example 1: maven test class
mvn install -Dmaven.test.skip=true
# or
mvn install -DskipTests
# If -Dmaven.test.skip=true (or simply -Dmaven.test.skip) is specified,
# the test-jars aren't built, and any module that relies on them will
# fail its build.
# In contrast, when you use -DskipTests, Maven does not run the tests,
# but it does compile them and build the test-jar, making it available
# for the subsequent modules.
Example 2: maven test class
private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();
private final PrintStream originalOut = System.out;
private final PrintStream originalErr = System.err;
@Before
public void setUpStreams() {
System.setOut(new PrintStream(outContent));
System.setErr(new PrintStream(errContent));
}
@After
public void restoreStreams() {
System.setOut(originalOut);
System.setErr(originalErr);
}
sample test cases:
@Test
public void out() {
System.out.print("hello");
assertEquals("hello", outContent.toString());
}
@Test
public void err() {
System.err.print("hello again");
assertEquals("hello again", errContent.toString());
}
Example 3: maven test class
@Test
void testExpectedException() {
Assertions.assertThrows(NumberFormatException.class, () -> {
Integer.parseInt("One");
});
}
Example 4: maven test class
# Run all the unit test classes.
$ mvn test
# Run a single test class.
$ mvn -Dtest=TestApp1 test
# Run multiple test classes.
$ mvn -Dtest=TestApp1,TestApp2 test
# Run a single test method from a test class.
$ mvn -Dtest=TestApp1#methodname test
# Run all test methods that match pattern 'testHello*' from a test class.
$ mvn -Dtest=TestApp1#testHello* test
# Run all test methods match pattern 'testHello*' and 'testMagic*' from a test class.
$ mvn -Dtest=TestApp1#testHello*+testMagic* test