JUnit quick start, writing first test

[Updated: Nov 11, 2017, Created: Mar 9, 2017]

What is JUnit?

JUnit is a unit testing framework for the Java programming language.

Writing a simple test

Create a simple maven project and add junit dependency if it's not already there:

 <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
 </dependency>

A Java class to test

public class Calc {
  public int multiply(int a, int b) {
      return a * b;
  }
}

Testing the method

Let's write a JUnit class to test Calc#mutlipy() method.

public class CalcTest {

  @Test
  public void testMultiply() {
      Calc c = new Calc();
      int i = c.multiply(3, 5);
      Assert.assertEquals(i, 15);
  }
}

JUnit's @org.junit.Test annotation is used on methods which execute the tests. org.junit.Assert class has many overloaded static methods to test conditions like assertEquals(..), assertNotEquals(..), assetTrue(..), assetFalse(..) etc. These methods throw exception (AssertionError) if the expected condition doesn't satisfy, which causes the test to fail.

Running the test

Let's import the project to our IDE. All IDE support JUnit test and provide convenient ways to run JUnit tests.

Running in Intellij

From 'Project' tool window, right click the file 'CalcTest.java' and select 'run...'

We can also run the test from Editor > right click menu.

On running the test it will either pass or fail. In our example:


Running in Eclipse

Eclipse has similar right click menu to run JUnit test:

Run the test:

Running in maven

Running all test classes (run from project root):

mvn test

Running only one test class:

mvn -q test -Dtest=CalcTest
D:\example-projects\junit\junit-quick-start>mvn -q test -Dtest=CalcTest

-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.logicbig.example.CalcTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.036 sec

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

Checkout more related maven commands here

JUnit framework uses reflection to run methods annotated with @Test.


Example Project

Dependencies and Technologies Used :

  • junit 4.12: JUnit is a unit testing framework for Java, created by Erich Gamma and Kent Beck.
  • JDK 1.8
  • Maven 3.3.9

Junit Quick Start Select All Download
  • junit-quick-start
    • src
      • main
        • java
          • com
            • logicbig
              • example
      • test
        • java
          • com
            • logicbig
              • example

See Also