Maven does not find JUnit tests to run

By default Maven uses the following naming conventions when looking for tests to run: Test* *Test *Tests (has been added in Maven Surefire Plugin 2.20) *TestCase If your test class doesn’t follow these conventions you should rename it or configure Maven Surefire Plugin to use another pattern for test classes.

How to mock a final class with mockito

Mockito 2 now supports final classes and methods! But for now that’s an “incubating” feature. It requires some steps to activate it which are described in What’s New in Mockito 2: Mocking of final classes and methods is an incubating, opt-in feature. It uses a combination of Java agent instrumentation and subclassing in order to … Read more

How to run test methods in specific order in JUnit4?

If you get rid of your existing instance of Junit, and download JUnit 4.11 or greater in the build path, the following code will execute the test methods in the order of their names, sorted in ascending order: import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class SampleTest { @Test public void testAcreate() { System.out.println(“first”); … Read more

JUnit test for System.out.println()

using ByteArrayOutputStream and System.setXXX is simple: 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 … Read more

How to run JUnit test cases from the command line

For JUnit 5.x it’s: java -jar junit-platform-console-standalone-<version>.jar <Options> Find a brief summary at https://stackoverflow.com/a/52373592/1431016 and full details at https://junit.org/junit5/docs/current/user-guide/#running-tests-console-launcher For JUnit 4.X it’s really: java -cp .:/usr/share/java/junit.jar org.junit.runner.JUnitCore [test class name] But if you are using JUnit 3.X note the class name is different: java -cp .:/usr/share/java/junit.jar junit.textui.TestRunner [test class name] You might need to … Read more