All Posts

JUnit – Unit Testing Framework

JUnit – Unit Testing Framework

JUnit is a simple, open-source Unit Testing framework tool for writing and running repeatable unit tests. It is also an instance of the xUnit architecture for unit testing frameworks. Most developers use it as a Unit testing tool.

What is Unit Testing?

 

JUnit Features

JUnit’s main features are as follows:

  • Annotations are used to mark the methods as test methods.
  • Assertions are needed to test expected results/actual results.

Test runner for running tests is shown in the picture below.

 

 

Unit Testing

 

JUnit 4 Maven dependency

If your build tool is Maven, add a dependency to JUnit to pom.xml. Replace the minor version to the latest stable version.

<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.xx</version>
  <scope>test</scope>
</dependency>

JUnit 4 Annotations

Annotations mark the tests as test cases ex: with @Test. The most common JUnit 4 annotations are:

@Test
@Before
@After

A simple JUnit test

The @Test annotation tells JUnit that the method to which it is attached can be run as a test case. JUnit first constructs a fresh class instance to run the method and then invokes the annotated method. In addition, JUnit will report any exceptions the test throws as a failure. If no exceptions are thrown, the test is assumed to have succeeded.

 

@Test 
public void testMethod() { 
assertEquals(1, 1); 
}

 

In conclusion, JUnit is the most recommended tool for writing/executing Java unit tests. JUnit 4 is a major API revision release ( However, a new version, JUnit5, is around the corner).

 

JUnit Tutorial on this website can be found at: