Open In App

Run JUnit Test Cases From the Command Line

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

JUnit allows us to test individual pieces of code by creating test cases, typically for methods and classes. Running tests via the command line can be beneficial for CI/CD pipeline scripts or when the environment does not support an IDE.

JUnit supports integration with several build tools, such as Maven and Gradle, which can simplify the process of running tests. This article will cover both approaches, as well as running JUnit tests manually from the command line without build tools.

Main Concept of Unit Testing

What is Unit Testing?

Unit testing refers to testing the smallest parts of the application, typically individual methods or classes, to ensure they work as expected. These tests focus on individual functionalities and are run in isolation from other parts of the system.

Unit testing ensures that each function or method in the application behaves as intended under various conditions, such as normal input, boundary cases, and invalid input. It is one of the earliest stages of testing in the software development lifecycle.

Importance of Unit Testing

  • Early Bug Detection: By testing each component of the application separately, we can catch bugs early, often before the code is integrated into larger parts of the system.
  • Simplified Debugging: Since the tests are for individual units, errors are easier to identify and resolve.
  • Documentation: Well-written unit tests serve as documentation for how the code is expected to behave.
  • Automated Regression Testing: Unit tests provide a safety net during refactoring or feature updates, ensuring that previous functionality remains intact.

JUnit facilitates unit testing in Java by providing annotations like @Test, assertions like assertEquals(), and powerful testing features such as parameterized tests and exception testing.

Why Run JUnit Tests from the Command Line?

Running JUnit test cases from the command line is important for several reasons:

  • Integration with CI/CD Pipelines: In automated build pipelines, running tests via command line tools like Maven or Gradle ensures code correctness after every commit.
  • Environment Flexibility: We may not always have an IDE or graphical environment, such as on remote servers.
  • Scripted Test Runs: Automating test runs through shell scripts or batch files enables continuous testing.

Example Project

Step 1: Create a New Maven Project

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

  • Name: JunitExample
  • Build System: Maven

Click on the Create button.

Project Metadata

Project Structure

Once created, the project structure should look like this:

Project Folder Structure

Step 3: Add JUnit Dependencies to pom.xml

Open the pom.xml file and add the following dependencies to your Maven project:

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>JUnitExample</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 5 dependencies -->
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>5.7.0</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>5.7.0</version>
            <scope>test</scope>
        </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>

Step 4: Create the StringUtility Class

Create the StringUtility class to provide methods for string manipulation.

Java
package com.gfg;

public class StringUtility {

    // Reverses the given string
    public String reverse(String input) {
        if (input == null) {
            throw new IllegalArgumentException("Input cannot be null"); // Check for null input
        }
        return new StringBuilder(input).reverse().toString(); // Reverse the string
    }

    // Converts the string to uppercase
    public String toUpperCase(String input) {
        if (input == null) {
            throw new IllegalArgumentException("Input cannot be null"); // Check for null input
        }
        return input.toUpperCase(); // Convert string to uppercase
    }

    // Counts the number of vowels in a string
    public int countVowels(String input) {
        if (input == null) {
            throw new IllegalArgumentException("Input cannot be null"); // Check for null input
        }
        int count = 0; // Initialize vowel count
        for (char c : input.toLowerCase().toCharArray()) { // Convert to lowercase and iterate
            if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
                count++; // Increment count if a vowel is found
            }
        }
        return count; // Return the total count of vowels
    }
}

Step 5: Main Class

Create the Main class to demonstrate the functionality of the StringUtility class.

Java
package com.gfg;

// Main class to demonstrate StringUtility functionality
public class Main {
    public static void main(String[] args) {
        StringUtility stringUtility = new StringUtility(); // Instantiate StringUtility

        // Test reverse method
        String reversed = stringUtility.reverse("example");
        System.out.println("Reversed: " + reversed); // Output reversed string

        // Test toUpperCase method
        String upper = stringUtility.toUpperCase("example");
        System.out.println("Uppercase: " + upper); // Output uppercase string

        // Test countVowels method
        int vowelCount = stringUtility.countVowels("example");
        System.out.println("Vowel count: " + vowelCount); // Output count of vowels
    }
}

Step 6: Write JUnit Test Cases for StringUtility

Create the StringUtilityTest class to write test cases for the StringUtility methods.

Java
import com.gfg.StringUtility;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

// Test class for StringUtility
class StringUtilityTest {

    private final StringUtility stringUtility = new StringUtility(); // Instantiate StringUtility

    @Test
    void testReverse() {
        assertEquals("tac", stringUtility.reverse("cat"), "Reverse test failed"); // Test reverse method
        assertEquals("", stringUtility.reverse(""), "Reverse empty string failed"); // Test empty string
        assertThrows(IllegalArgumentException.class, () -> stringUtility.reverse(null), "Null input failed"); // Test null input
    }

    @Test
    void testToUpperCase() {
        assertEquals("HELLO", stringUtility.toUpperCase("hello"), "Uppercase conversion failed"); // Test lowercase input
        assertEquals("WORLD", stringUtility.toUpperCase("WoRlD"), "Mixed case conversion failed"); // Test mixed case
        assertThrows(IllegalArgumentException.class, () -> stringUtility.toUpperCase(null), "Null input failed"); // Test null input
    }

    @Test
    void testCountVowels() {
        assertEquals(3, stringUtility.countVowels("example"), "Vowel count failed"); // Test count of vowels
        assertEquals(0, stringUtility.countVowels("xyz"), "Vowel count for consonants failed"); // Test no vowels
        assertThrows(IllegalArgumentException.class, () -> stringUtility.countVowels(null), "Null input failed"); // Test null input
    }
}

Step 7: Run the Application

Once the project is completed, it will run and show the below output:

Output

Step 8: Running Tests using command line

In the terminal, navigate to the directory to your project folder and use the following command to run the tests:

mvn test

Output:

Test Output


Test Results:

Test Results



Next Article
Article Tags :

Similar Reads