Skip to main content

JUnit

Junit is a testing framework that was designed for JVM. It allows you to encase your code in a testing workflow template. 

What Does this Mean?

The default unit testing template defines one method for setting up the test, one method for executing the test, and one test for cleaning up once the test has been executed (whether the test succeeded or not). Consider the code template below:

JUnit Class Example Expand source

import org.junit.*;

public class JUnitExample {

@BeforeClass
public static void setUpTestClass() {
System.out.println("--- START : run tests from class ---");
}

@Before
public void setUpTestMethod() {
System.out.println("--- About to ENTER test method ---");
}

@Test
public void test1() {
System.out.println("I'm test1");
}

@Test
public void test2() {
System.out.println("I'm test2");
}

@After
public void tearDownMethod() {
System.out.println("--- About to EXIT test method ---");
}

@AfterClass
public static void tearDownClass() {
System.out.println("--- FINISH : tests from class --- ");
}

}


Output :


--- START : run tests from class ---
--- About to ENTER test method ---
I'm test1
--- About to EXIT test method ---
--- About to ENTER test method ---
I'm test2
--- About to EXIT test method ---
--- FINISH : tests from class ---


As you can see, each method is marked with an annotation that defines its role in the test workflow:

@BeforeClass - This method will set up the test Class (e.g runs once before all @Test methods are executed in the class context)

@Before - This method that prepares all the parameters needed for a @Test Method. It is annotated as @Before because it runs before the test method.

@Test - the method where the test steps are defined, annotated with @Test of course.

@After - the method that cleans up after the  @Test Method has finished running, runs after the test method has finished running.

@AfterClass -  This method tear downs after the execution of all @Test methods in the class (e.g runs once after all @Test methods are executed in the class context)

Without JUnit, you would have to create an instance of the test class and run inside a static main method. JUnit frees from the need to write create a class test instance and run it in some main method. Like we always like to say, No Hassle!

Getting Started with JUnit

To use JUnit, you should obtain the required JUnit dependencies. You can do it in one of two ways:

  1. Download JUnit .jars and add it to your project's classpath.
  2. Get the jar by specifying the dependency in Gradle.

The second method, using Gradle is the better way because it allows you to export your project to other team members or host it in a git repository.

To learn more about JUnit, visit their documentation.