Show List

Set Up

JUnit is testing framework for Java so we need Java to be installed on the system. Refer to Java Environment Set Up for JDK installation.

JUnit can be set up in a few different ways, depending on the development environment and tools being used. Here are two common approaches to setting up JUnit:

  1. Using a build tool such as Maven or Gradle: In this setup, JUnit is added as a dependency in the project's build file (pom.xml for Maven and build.gradle for Gradle). The build tool will automatically download and include the JUnit library in the project's classpath, allowing you to write and run JUnit tests. Here is an example of adding JUnit as a dependency in a Maven project:
     junit-jupiter-api and junit-jupiter-engine are the two dependencies that need to be added
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>org.example</groupId>
<artifactId>Unit-Test-Demo</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.7.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.7.2</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
  1. Downloading and adding the JUnit library manually: In this setup, the JUnit library is downloaded manually and added to the project's classpath. This can be done by downloading the JUnit jar file from the JUnit website and adding it to the project's build path in your IDE.

Once JUnit is set up, you can write and run JUnit tests. To write a JUnit test, you simply need to create a Java class and annotate it with the @Test annotation. Here is an example of a simple JUnit test:

import org.junit.Test;

public class ExampleTest {
   @Test
   public void testExample() {
      int a = 1;
      int b = 2;
      assertEquals(3, a + b);
   }
}
This test can be run from the command line, integrated into a build process, or executed from within an IDE. To run the test, you simply need to run the test class or use a test runner provided by JUnit. The test runner will execute all tests in the class and provide a detailed report of the test results.

    Leave a Comment


  • captcha text