Проект Maven — проверка и тестирование телефонных номеров через JUnit

Опубликовано: 19 Февраля, 2023

Любое веб/мобильное/консольное приложение должно быть безошибочным и, следовательно, должно пройти множество проверок. В этой статье давайте посмотрим, как проверять номера телефонов с кодами стран и без них, а также тестировать их с помощью JUNIT, чтобы проверить, верны ли данные тестируемые номера телефонов. С помощью проекта maven сделаем то же самое.

Пример проекта

Структура проекта:

Проект Maven и, следовательно, зависимости находятся в

пом.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>

Во-первых, давайте напишем проверки, необходимые для проверки номера телефона.

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());
    }
  
}

Теперь давайте приступим к написанию 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")));
             
    }
}

Здесь мы должны отметить, что

утверждать все:

Групповые проверки можно выполнять с помощью assertAll, и если кто-то утверждает, что это неверно, то весь оператор будет не выполнен. Вместо того, чтобы писать несколько ассеров, таким образом можно сделать группировку. Более того, иногда есть ссылка на то, что все условия должны быть выполнены для данного бизнес-варианта. В такие моменты assertAll очень помогает. Вот в нашем примере для демонстрации рабочего процесса мы взяли 2 набора

// 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 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")));

Следовательно, наш вывод будет

Таким образом, JUnit помогает нам улучшать качество программного обеспечения. Нам нужно использовать несколько утверждений, а также необходимо опробовать множество тестовых случаев, чтобы можно было улучшить качество программного обеспечения.