Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Tutorial
  • Java Spring
  • Spring Interview Questions
  • Java SpringBoot
  • Spring Boot Interview Questions
  • Spring MVC
  • Spring MVC Interview Questions
  • Java Hibernate
  • Hibernate Interview Questions
  • Advance Java Projects
  • Java Interview Questions
Open In App
Next Article:
JUnit – Executing Tests with Maven Build
Next article icon

JUnit – Executing Tests with Maven Build

Last Updated : 03 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

JUnit is a widely-used testing framework for Java that allows developers to create and execute unit tests. When combined with Maven, the build automation tool, it becomes easy to automate the execution of these tests as part of the build lifecycle. In this article, we will explore how JUnit works with Maven, how to set up the project, and how to run the tests efficiently.

Understanding Maven and JUnit Integration

Maven

Maven is a build automation and project management tool that simplifies managing project dependencies, building, testing, and packaging applications. It uses the Project Object Model (POM) file to define project structure, dependencies, and build configurations.

JUnit

JUnit is a Java testing framework used for testing individual units of source code. It allows developers to write test cases for methods and functionalities in isolation and verify that they produce the expected outcomes.

Maven and JUnit Integration

Maven integrates with JUnit through the Maven Surefire Plugin, responsible for running unit tests during the build process. When you run a Maven build, the Surefire Plugin automatically detects and runs test cases located in the src/test/java directory. These test cases are typically written using JUnit.

Maven follows a build lifecycle, where each lifecycle phase performs a specific task. The test phase is the step in the lifecycle where Maven runs the JUnit tests.

Lifecycle Phases in Maven:

  • compile: Compiles the source code.
  • test: Runs unit tests using the Surefire Plugin and JUnit.
  • package: Packages the compiled code into a JAR or WAR file.
  • install: Installs the built package into the local Maven repository.

JUnit Testing with Maven

This example project demonstrates how to set up JUnit tests with Maven. The project includes a simple Java class (Calculator) with methods to add and subtract numbers, along with the corresponding JUnit test class (CalculatorTest) to validate these methods.

Step 1: Create a New Maven Project

Create a new Maven project using IntelliJ IDEA. Choose the following options:

  • Name: JUnitMavenExample
  • Build system: Maven
  • Click on the Create button.
Project Metadata

Project Structure

After the project creation done successfully, then the folder structure will look like the below image:

Project Folder Structure

Step 2: Add Dependencies to pom.xml

Open the pom.xml file and add the JUnit dependency, which is necessary for running the JUnit tests.

XML
<?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>com.gfg</groupId>     <artifactId>JUnitMavenExample</artifactId>     <version>1.0-SNAPSHOT</version>      <properties>         <maven.compiler.source>17</maven.compiler.source>         <maven.compiler.target>17</maven.compiler.target>         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>     </properties>      <dependencies>         <!-- JUnit dependency for testing -->         <dependency>             <groupId>junit</groupId>             <artifactId>junit</artifactId>             <version>4.13.2</version>             <scope>test</scope> <!-- Indicates that this dependency is only required for the test phase -->         </dependency>     </dependencies>      <build>         <plugins>             <plugin>                 <groupId>org.apache.maven.plugins</groupId>                 <artifactId>maven-surefire-plugin</artifactId>                 <version>2.22.2</version>             </plugin>         </plugins>     </build> </project> 

The JUnit dependency is included with the test scope, meaning it's only used during the test phase. The maven-surefire-plugin ensures the tests are executed during the build process.

Step 3: Create the Calculator Class

Create the Calculator class, which will have basic arithmetic methods: add() and subtract().

Calculator.java

Java
package com.gfg;  public class Calculator {     // Method to add two numbers     public int add(int a, int b) {         return a + b; // Returns the sum of a and b     }      // Method to subtract one number from another     public int subtract(int a, int b) {         return a - b; // Returns the difference of a and b     } } 
  • add(int a, int b): This method adds the two numbers and returns the result.
  • subtract(int a, int b): This method subtracts the second number from the first number.

Step 4: Create the Main Class

Create the Main class to perform the basic arithmetic operations and demonstrate the use of the Calculator class.

Main.java

Java
package com.gfg;  //TIP To <b>Run</b> code, press <shortcut actionId="Run"/> or // click the <icon src="AllIcons.Actions.Execute"/> icon in the gutter. public class Main {     public static void main(String[] args) {         Calculator calculator = new Calculator();          // Example of adding two numbers         int sum = calculator.add(5, 3);         System.out.println("Sum of 5 and 3 is: " + sum);            // Example of subtracting two numbers         int difference = calculator.subtract(5, 3);         System.out.println("Difference of 5 and 3 is: " + difference);     } } 

The main method allows for the standalone execution of the class. It demonstrates the use of the add and subtract methods by creating an instance of the Calculator class and printing the results to the console.

Step 5: Create the JUnit Test Class

Create the CalculatorTest class containing test methods to verify the functionality of the Calculator class.

CalculatorTest.java

Java
import com.gfg.Calculator; import org.junit.Test; import static org.junit.Assert.assertEquals;  public class CalculatorTest {     // Instantiate the Calculator object     Calculator calculator = new Calculator();      // Test for the add method     @Test     public void testAdd() {         int result = calculator.add(2, 3); // Calls the add method         assertEquals(5, result);  // Verifies if 2 + 3 equals 5     }      // Test for the subtract method     @Test     public void testSubtract() {         int result = calculator.subtract(5, 3); // Calls the subtract method         assertEquals(2, result);  // Verifies if 5 - 3 equals 2     } } 
  • testAdd(): Checks if the add() method of the Calculator returns the correct sum.
  • testSubtract(): Verifies the output of the subtract() method.
  • assertEquals(expected, actual): Asserts that the expected and actual values are the same.

Step 6: Run the Application

Once the project is complete, run the Main class, and you should see the following output:

Application Runs

Step 7: Run the Tests with Maven

To execute the tests, run the following Maven command in the project directory:

mvn test

This command compiles the code and runs the test cases located in the src/test/java directory.

Test Results:

Test Results

Step 8: Generated Test Report

Maven's Surefire Plugin automatically generates a test report in the target/surefire-reports/ directory.

  • Surefire report file: target/surefire-reports/CalculatorTest.txt
    This file contains a detailed log of the test execution, including pass/fail status and stack traces for any failed tests.
Generate Test Report

This example project demonstrates how to set up the Maven project to work with JUnit, including, Creating the simple Calculator class with arithmetic methods and writing the corresponding the JUnit test class to verify the behavior of the Calculator class, Running the tests using the Maven command (mvn test) and viewing the generated reports.

Conclusion

Integrating JUnit with Maven allows developers to automate testing as part of the build lifecycle, ensuring code quality and minimizing bugs. By understanding Maven's build lifecycle and configuring the Surefire Plugin, you can customize how and when tests are executed, generate reports, and optimize the testing process. For more advanced testing strategies, consider exploring JUnit 5 and its new features, such as parameterized tests and dynamic tests.


Next Article
JUnit – Executing Tests with Maven Build

G

geekforgs9hp
Improve
Article Tags :
  • Advance Java
  • JUnit

Similar Reads

    Building a Java Project with Maven
    Maven is one of the most popular build automation tools. It is developed using the Java programming language and is primarily used for Java-based projects. However, it has been updated to support programming languages like C#, Ruby, and more. This article will teach us how to build a Java project wi
    2 min read
    Why Maven Doesn’t Find JUnit Tests to Run?
    When Maven fails to find JUnit tests to run, it can be frustrating and disrupt the development process. Several common issues can cause this problem, ranging from incorrect directory structures, missing dependencies, and to misconfigured plugins. One common issue developers face when using Maven is
    2 min read
    JUnit 5 – Execute Test in Eclipse
    JUnit is one of the widely used unit testing frameworks for Java-based Applications. We have different versions and upgrades published by JUnit 5, the latest version available in JUnit is JUnit 5. JUnit 5 is the upgraded version of JUnit 4, which is launched to support various latest features of Jav
    10 min read
    JUnit 5 – Conditional Test Execution
    JUnit is one of the popular unit testing frameworks for Java projects. JUnit 5 is the latest version provided by the JUnit team launched with the aim of supporting the latest Java features and also providing notable advanced features to its predecessor JUnit 4. In this article, we will discuss one o
    8 min read
    Tagging and Filtering JUnit Tests
    JUnit is a widely used testing framework for Java applications that allows developers to write unit tests for their code. One of its powerful features is the ability to tag and filter tests. This feature is useful when running a subset of the tests under different conditions, such as during developm
    9 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences