Open In App

JUnit – Sample Test Cases for String Java Service

Last Updated : 11 Oct, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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:

Project Structure

 

It is a maven project. Hence let’s start with pom.xml

pom.xml

XML




<?xml version="1.0" encoding="UTF-8"?>
         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>
        <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.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads