Run JUnit Test Cases From the Command Line
Last Updated :
21 Oct, 2024
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 Structure
Once created, the project structure should look like this:
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:
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 Results:
Similar Reads
How to run TestNG from command line?
Running TestNG from the command line is a powerful technique for managing your automated tests efficiently. TestNG is a popular testing framework that provides various features for running and configuring tests. While IDE-based execution is common, using the command line offers greater flexibility a
4 min read
How to run multiple test classes in TestNG?
TestNG makes it easy to run multiple test classes in one go, which helps test different parts of an application efficiently. By running multiple classes together, you save time and ensure more thorough testing. You can run these classes using a TestNG XML file, directly from Eclipse, or through the
2 min read
How to call shell commands from Ruby?
Ruby, known for its simplicity and productivity, offers several ways to call shell commands. This capability is useful for various tasks such as automation, script integration, and system management. Here, we will explore different methods to execute shell commands from Ruby, including their usage a
3 min read
How do I run the pytest tests in Django?
Are you someone who wants to ensure the stability and reliability of their application then testing Django is a very important step you need to perform. Not just this but pytest is a very popular testing framework for Python which provides a simple yet powerful way to write and run tests. For people
4 min read
How to Run Specific TestNG Suite with Maven from Command Line?
When using Maven as your build automation tool and TestNG for Java-based testing, you may need to execute particular test suites instead of running every test. Running test subsets according to functionality, environment, or any other criteria can be helpful in this regard. You must set up your Mave
2 min read
JUnit - Sample Test Cases for String Java Service
Always automated testing helps to overcome various bugs. It will help in the integrity of the software as well. Here in this article, let us see how to write JUnit test cases for various String-related functions like "Isogram, Panagram, Anagram" etc., In the entire lifecycle of a software project, w
5 min read
How to Run Postman Scripts from Newman CLI Commands
Postman is an API development tool that allows developers to create, test, and manage APIs effortlessly. This helps in simplifying the testing and validation of APIs during the development process. In simple terms, it is an API that acts as a bridge that allows the different applications to communic
5 min read
Running Custom Django manage.py Commands in Tests
Django's manage.py commands are powerful tools for performing various administrative tasks. Sometimes, you might want to call these custom commands directly from your test suite to test their functionality or to set up the environment for your tests. In this article, we will walk through the process
2 min read
How to Rerun the Failures in a BDD Junit Test Automation Framework?
We come across failures many times after we execute our test scenarios through automation. These failures can be because of majorly two reasons: Functional Issue (actual failure).Intermittent Issues (Application Slowness, Page not loaded properly, Technical Issue, etc.). Having a mechanism to automa
7 min read
Running a Single Test or Method With Maven
Running a single test or method using Maven is straightforward and can be accomplished using Maven commands. By default, Maven runs all tests in your project, but you can specify a single test class or even a single test method to execute. In this article, we will learn how to run a single test or m
3 min read