Open In App

Maven Project – Phone Number Validations and Testing via JUnit

Last Updated : 15 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Any web/mobile/console application should be error-free and hence it has to undergo a lot of validations. In this article, let us see how to validate phone numbers with and without country codes and test the same via JUNIT to check whether the given testing phone numbers are correct or not. Via a maven project, let us do the same.

Example Project

Project Structure:

Project Structure

 

Maven project and hence dependencies are in

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.UtilityServices</groupId>
    <artifactId>UtilityServices</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>UtilityServices</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.UtilityServices.*UtilityServices*</param>
                          
                    </targetClasses>
                    <targetTests>
                        <param>com.gfg.UtilityServices.*</param>
                    </targetTests>
                </configuration>
            </plugin>
  
        </plugins>
    </build>
  
</project>


First, let us write the validations that are needed for phone number validation

UtilityServices.java

Java




import java.util.regex.Matcher;
import java.util.regex.Pattern;
  
public class UtilityServices {
    public boolean checkValidPhoneWithoutCountryCode(String phoneNumber) {
        Pattern phoneNumberPattern = Pattern.compile("^\\d{10}$");
           
        // matcher() method helps
        // to find matching between given number
        // and regular expression 
        Matcher findAMatch = phoneNumberPattern.matcher(phoneNumber);
   
        // Returning boolean value
        return (findAMatch.matches());
    }
  
    public boolean checkValidPhoneWithCountryCode(String phoneNumber) {
        Pattern phoneNumberPattern = Pattern.compile(
                "^(\\+\\d{1,3}( )?)?((\\(\\d{1,3}\\))|\\d{1,3})[- .]?\\d{3,4}[- .]?\\d{4}$");
           
        // matcher() method helps
        // to find matching between given number
        // and regular expression 
        Matcher findAMatch = phoneNumberPattern.matcher(phoneNumber);
   
        // Returning boolean value
        return (findAMatch.matches());
    }
  
}


Now let us proceed to go into writing JUNIT

Java




import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeFalse;
import static org.junit.jupiter.api.Assumptions.assumingThat;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
  
public class TestUtilityService {
    
    @Test
    public void testForValidPhoneNumbersWithoutCoutryCode() {
        UtilityServices phoneNumberService = new UtilityServices();
        assertEquals(true, phoneNumberService.checkValidPhoneWithoutCountryCode("1234567890"));
        assertNotEquals(true, phoneNumberService.checkValidPhoneWithoutCountryCode("13579"));
        assertEquals(true, phoneNumberService.checkValidPhoneWithoutCountryCode("1122334455"));
        assertTrue(phoneNumberService.checkValidPhoneWithoutCountryCode("2244668800"));
        assertFalse(phoneNumberService.checkValidPhoneWithoutCountryCode("13ab@A"),"Invalid PhoneNumber");
        String validationName = "phoneNumberValidation";
          
        // In a grouped assertion all assertions
        // are executed, and any
        // failures will be reported together.
        assertAll("phoneNumberValidation", () -> assertTrue(phoneNumberService.checkValidPhoneWithoutCountryCode("1357924680")),
                () -> assertTrue(phoneNumberService.checkValidPhoneWithoutCountryCode("1234567890")));
        // Let us comment for the first time
        // assertAll("phoneNumberValidationYieldingFalse", () -> assertTrue(phoneNumberService.checkValidPhoneWithoutCountryCode("abcd12@gfg.com")),
        //       () -> assertFalse(phoneNumberService.checkValidPhoneWithoutCountryCode("12345Abc@d")));
          
        // The assumingThat() method executes the rest of the statements 
        // if the assumption is valid. If the assumption is invalid, 
        // this method does nothing. 
        // Advantage : To log the information
       assumingThat("phoneNumberValidation".equals(validationName), () -> {
            System.out.println("Checking for phone number validation!!!");
            assertEquals(true, phoneNumberService.checkValidPhoneWithoutCountryCode("9988776612"));
        });
         
        // with assumeFalse
        // If the boolean condition in assumeFalse becomes 
        // false then only the next set of test method is executed, 
        // else the test is skipped.        
        assumeFalse("loginValidation".equals(validationName));
        assertTrue(phoneNumberService.checkValidPhoneWithoutCountryCode("9977661244"));
        assertArrayEquals(new long[]{9940123456L,9940123457L,9940123458L},new long[]{9940123456L,9940123457L,9940123458L});
        Assertions.assertThrows(IllegalArgumentException.class, () -> {
            Integer.parseInt("one two 3 4 5 6 7 8 nine 0");
        });
        
    }
      
    @Test
    public void testForValidPhoneNumbersWithCoutryCode() {
        UtilityServices phoneNumberService = new UtilityServices();
        assertEquals(true, phoneNumberService.checkValidPhoneWithCountryCode("+91 1234567890"));
        assertNotEquals(true, phoneNumberService.checkValidPhoneWithoutCountryCode("13579"));
        assertEquals(true, phoneNumberService.checkValidPhoneWithCountryCode("+1 1122334455"));
        assertTrue(phoneNumberService.checkValidPhoneWithCountryCode("+61 2244668800"));
        assertFalse(phoneNumberService.checkValidPhoneWithCountryCode("+61 131211"),"Invalid PhoneNumber");
         
         // In a grouped assertion all assertions are executed, and any
        // failures will be reported together.
        assertAll("phoneNumberValidation", () -> assertTrue(phoneNumberService.checkValidPhoneWithCountryCode("+64 1357924680")),
                () -> assertTrue(phoneNumberService.checkValidPhoneWithCountryCode("+57 1234567890")));
             
    }
}


Here we need to note that

assertAll:

Grouped checks can be done by using assertAll and if there is anyone assert is wrong, then the whole statement will be failed. Instead of writing multiple assers, grouping can be done in this way. Moreover, sometimes there is a link like, all the conditions need to be met for a given business use case. During those times, assertAll helps a lot. Here in our example, to demonstrate the workflow, we have taken 2 sets

// In a grouped assertion all assertions are executed, and any
// failures will be reported together.
assertAll("phoneNumberValidation", () -> assertTrue(phoneNumberService.checkValidPhoneWithoutCountryCode("1357924680")),
                () -> assertTrue(phoneNumberService.checkValidPhoneWithoutCountryCode("1234567890")));
    

Actually below set of code got commented out. Hence we are getting all test cases passed

assertArrayEquals:

This is also a good facility to group items together and check. For example, to check all the person’s mobile number values with the expected values, this can be used, instead of one by one. On running the above code, we can see the below output.

 

// Let us uncomment now for the second  time, as blocked portion is wrong. 
i.e. the first assertTrue. It is not a valid phone number
// Though second assertFalse provides the correct result, as they are grouped with assertAll, we will get error only  
assertAll("phoneNumberValidationYieldingFalse", () -> 
assertTrue(phoneNumberService.checkValidPhoneWithoutCountryCode("abcd12@gfg.com")),
() -> assertFalse(phoneNumberService.checkValidPhoneWithoutCountryCode("12345Abc@d")));

Hence our output would be

 

Thus JUnit helps us to improve the quality of software. We need to use multiple asserts and also lot of test cases need to be tried out so that the software quality can be improved.



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

Similar Reads