JUnit - Sample Test Cases for String Java Service
Last Updated :
11 Oct, 2022
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, we may come across in writing this kind of functionalities either as an individual unit or as the middle of a software code. As a sample, let us see how to write the business logic as well as JUnit test cases for the same. Via a maven project, let us see the same.
Example Project
Project Structure:
It is a maven project. Hence let's start with pom.xml
pom.xml
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.StringServicesJava</groupId>
<artifactId>StringServicesJava</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<properties>
<!-- https://maven.apache.org/general.html#encoding-warning -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<junit.version>5.3.1</junit.version>
<pitest.version>1.4.3</pitest.version>
</properties>
<dependencies>
<!-- junit 5, unit test -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>maven-mutation-testing</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M1</version>
</plugin>
<plugin>
<groupId>org.pitest</groupId>
<artifactId>pitest-maven</artifactId>
<version>${pitest.version}</version>
<executions>
<execution>
<id>pit-report</id>
<phase>test</phase>
<goals>
<goal>mutationCoverage</goal>
</goals>
</execution>
</executions>
<!-- https://github.com/hcoles/pitest/issues/284 -->
<!-- Need this to support JUnit 5 -->
<dependencies>
<dependency>
<groupId>org.pitest</groupId>
<artifactId>pitest-junit5-plugin</artifactId>
<version>0.8</version>
</dependency>
</dependencies>
<configuration>
<targetClasses>
<param>com.gfg.StringServicesJava.*StringServicesJava*</param>
</targetClasses>
<targetTests>
<param>com.gfg.StringServicesJava.*</param>
</targetTests>
</configuration>
</plugin>
</plugins>
</build>
</project>
Whatever business logic, we need to write, let's keep them under the src folder of a project
StringServicesJava.java
Java
import java.util.Arrays;
public class StringServicesJava {
// No alphabet should be repeated more than once
public boolean checkIsogram(String inputString)
{
// always it is good to convert the string in either
// lower/upper case because for isogram irrespective
// of the case we need to check that no alphabet
// should be occurred more than once.
inputString = inputString.toLowerCase();
int stringLength = inputString.length();
char characterArray[] = inputString.toCharArray();
// This will help to sort the alphabets
Arrays.sort(characterArray);
for (int i = 0; i < stringLength - 1; i++) {
if (characterArray[i] == characterArray[i + 1])
return false;
}
return true;
}
// If the given string contains all the letters from a
// to z (before that let us convert the given string into
// lowercase) then it is a panagram
public boolean checkPanagram(String inputString)
{
// always it is good to convert the string in either
// lower/upper case because for panagram
// irrespective of the case we need to check that
// all alphabets should be present.
inputString = inputString.toLowerCase();
boolean isAllAlphabetPresent = true;
// Loop over each character itself
for (char ch = 'a'; ch <= 'z'; ch++) {
// Using contains we can check whether the
// string contains the given alphabet. if it
// does not contain make the boolean variable
// false
if (!inputString.contains(String.valueOf(ch))) {
isAllAlphabetPresent = false;
break;
}
}
return isAllAlphabetPresent;
}
// While comparing two strings, if a string contains the
// same characters of another string but the order of the
// characters are different
public boolean checkAnagram(String inputString1,
String inputString2)
{
// always it is good to convert the string in either
// lower/upper case because for anagram
// irrespective of the case we need to check that
// alphabets are available in both the string.
inputString1 = inputString1.toLowerCase();
inputString2 = inputString2.toLowerCase();
int str1Length = inputString1.length();
int str2Length = inputString2.length();
// For anagram, only ordering is different but
// string lengthwise they should be equal
if (str1Length != str2Length) {
return false;
}
char[] str1 = inputString1.toCharArray();
char[] str2 = inputString2.toCharArray();
// Sort both strings
Arrays.sort(str1);
Arrays.sort(str2);
// Compare sorted strings
for (int index = 0; index < str1Length; index++) {
if (str1[index] != str2[index])
return false;
}
return true;
}
}
Corresponding JUNIT test cases are available below
TestStringServicesJava.java
Java
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
public class TestStringServicesJava {
@DisplayName("Test check for Isogram")
@Test
public void testCheckForIsogram() {
StringServicesJava stringServicesJavaObject = new StringServicesJava();
assertEquals(false, stringServicesJavaObject.checkIsogram("GeekForGeek"));
assertEquals(true, stringServicesJavaObject.checkIsogram("algorithm"));
assertEquals(false, stringServicesJavaObject.checkIsogram("datastructures"));
assertEquals(false, stringServicesJavaObject.checkIsogram("machinelearning"));
assertEquals(true, stringServicesJavaObject.checkIsogram("importance"));
}
@DisplayName("Test check for Panagram")
@Test
public void testCheckForPanagram() {
StringServicesJava stringServicesJavaObject = new StringServicesJava();
assertEquals(true, stringServicesJavaObject.checkPanagram("AbCDefGhIJklmnoPQRStuvWXyZ234"));
assertEquals(true, stringServicesJavaObject.checkPanagram("Pack my box with five dozen liquor jugs"));
assertEquals(true, stringServicesJavaObject.checkPanagram("Waltz, bad nymph, for quick jigs vex"));
assertEquals(false, stringServicesJavaObject.checkPanagram("machinelearning"));
assertEquals(false, stringServicesJavaObject.checkPanagram("importance"));
}
@DisplayName("Test check for Anagram")
@Test
public void testCheckForAnagram() {
StringServicesJava stringServicesJavaObject = new StringServicesJava();
assertEquals(true, stringServicesJavaObject.checkAnagram("Listen","silent"));
assertEquals(false, stringServicesJavaObject.checkAnagram("geeksforgeeks","geeks"));
assertEquals(true, stringServicesJavaObject.checkAnagram("a gentleman", "elegant man"));
assertEquals(true, stringServicesJavaObject.checkAnagram("geeksforgeeks","forgeeksgeeks"));
assertEquals(true, stringServicesJavaObject.checkAnagram("angel","glean"));
}
}
Easily JUNIT test cases can be run as below
Once our business logic is correct in all aspects and JUNIT is written in such a way to accommodate the same, we will get all the test cases passed.
In case of any error, in terms of business logic or the expected value and actual value do not match, then we will get as given in the below screenshot.
Conclusion
Always it is ideal to go with JUNIT test cases while preparing the software and the quality of the software is benchmarked against this.
Similar Reads
JUnit - Writing Sample Test Cases for StudentService in Java
In many parts of projects, collections play a major role. Among that ArrayList is a user-friendly collection and many times it will be required to develop software. Let us take a sample project that involves a "Student" model that contains attributes such as studentId, studentName, courseName, and G
5 min read
JUnit - Writing Sample Test Cases for CutOffMarkCalculation Java Service
The quality of the software is very important. Though Unit tests and integration tests are done in the manual testing way, we cannot expect all kinds of scenarios to test. Automated testing is more helpful. In this article, how to write JUnit for the cutoff marks calculation based on caste and marks
3 min read
CRUD JUnit Tests for Spring Data JPA
Learn how to create and test a Spring Data JPA repository using JUnit and Mockito in this comprehensive guide. We'll cover setting up the test environment, writing CRUD operations, and customizing queries. By following this guide, you will ensure the robustness of the data layer in your Spring Boot
8 min read
Writing Templates for Test Cases Using JUnit 5
Writing consistent and reusable test case templates is essential for maintaining quality and ensuring uniformity in large-scale projects. Test case templates provide a structured approach for documenting and executing test scenarios, making it easier to identify issues, automate testing, and validat
7 min read
Provider.Service toString() method in Java with Examples
The toString() method of java.security.Provider.Service class returns a string representation of this provider service. Syntax: public String toString() Return Value: This method provides string representation of this provider service. Below are the examples to illustrate the toString() method: Exam
2 min read
JUnit Testing For MySQL Project in Java
For testing a software project, automated testing is always good and that will produce error-prone results. In the case of manual testing, there are possibilities of human errors. In this article let us take a sample project and let us see how to write JUnit test cases for it. Example Project Projec
6 min read
Software Testing - Testing Telecom Domain with Sample Test Cases
Testing the telecom domain is a process of testing the telecom applications. The Telecom domain is a vast area to test. It involves testing a lot of hardware components, back-end components, and front-end components. The various products in this domain are BSS, OSS, NMS, Billing System, etc. In the
15+ min read
Test Case For Search Functionality
The search functionality of the software should allow users to search for specific content within the software. The search results should be displayed in a manner that is easy to understand and navigate. The article focuses on discussing test cases for the search functionality:Test Case For Search F
3 min read
Running JUnit Tests Programmatically, from a Java Application
JUnit is a popular testing framework in the Java ecosystem that enables developers to create and run tests efficiently. While it is common to run tests through IDEs or build tools, running them programmatically allows greater flexibility in integrating testing into various stages of the application
5 min read
Run JUnit Test Cases From the Command Line
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 Ma
5 min read