Dernière modification : 10/11/2022

Template basique de test Java

 

Template basique de test Java avec JUnit 5 (pour les tests unitaires) et Mockito (pour la création des bouchons (mock)).

 

Dans le fichier pom.xml, renseigner la version de Java (ici 17) :

<properties>
    <java.version>17</java.version>
    <maven.compiler.target>17</maven.compiler.target>
    <maven.compiler.source>17</maven.compiler.source>
</properties>

Insérer la dépendance Mockito dans le fichier pom.xml :

<!-- https://mvnrepository.com/artifact/org.mockito/mockito-core -->
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
    <version>3.3.3</version>
    <scope>test</scope>
</dependency>

Insérer la dépendance JUnit Jupiter dans le fichier pom.xml :

<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-engine</artifactId>
    <version>5.4.0</version>
    <scope>test</scope>
</dependency>

Ajouter également dans le fichier pom.xml, dans le noeud build > plugins les données suivantes, sans quoi les tests ne seraient pas exécutés lors d'un clean install :

<plugin>
	<groupId>org.apache.maven.plugins</groupId>
	<artifactId>maven-surefire-plugin</artifactId>
	<!-- JUnit 5 requires Surefire version 2.22.0 or higher -->
	<version>2.22.2</version>
</plugin>

Fichier pom.xml complet :

<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>GROUP_ID</groupId>
    <artifactId>ARTIFACT_ID</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <properties>
        <java.version>17</java.version>
        <maven.compiler.target>17</maven.compiler.target>
        <maven.compiler.source>17</maven.compiler.source>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
            <version>3.3.3</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>5.9.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <!-- JUnit 5 requires Surefire version 2.22.0 or higher -->
                <version>2.22.2</version>
            </plugin>
        </plugins>
    </build>
</project>

 

Service Decorator : DecoratorService.java :

/**
 * Decorator Service
 * @version 1.0
 */
public class DecoratorService {
    /**
     * Decorate the text with []
     * 
     * @param  txt the text
     * @return     the text decorated with []
     */
    public String decorate(String txt) {
        return "[" + txt + "]";
    }
}

Classe à tester : MyClass.java :

/**
 * My class
 * @version 1.0
 */
public class MyClass {
    /** My decorator service */
    private DecoratorService myDecoratorService;

    /**
     * Converts the text to uppercase decorated via {@code myDecoratorService}.
     * 
     * @param  txt the text
     * @return     the text to uppercase.
     */
    public String toUpperCase(String txt) {
        return myDecoratorService.decorate(txt.toUpperCase());
    }

    public DecoratorService getMyDecoratorService() {
        return myDecoratorService;
    }

    public void setMyDecoratorService(DecoratorService myDecoratorService) {
        this.myDecoratorService = myDecoratorService;
    }
}

Classe de test : MyClassTest.java :

/**
 * MyClass test
 * @version 1.0
 */
/*
 * If Autowired and database - Spring
 * @ExtendWith(SpringExtension.class) // (JUnit 5)
 * @RunWith(SpringJUnit4ClassRunner.class) // (JUnit 4)
 * @ContextConfiguration(locations = { "classpath:WEB-INF/web-context.xml" })
 * @WebAppConfiguration
 */
public class MyClassTest {
    /** Service to Mock */
    private DecoratorService decoratorService;

    /** Class to test */
    private MyClass myClass;

    /**
     * Initialization
     */
    @BeforeEach // @Before in JUnit 4
    public void initialization() {
        // Mock objects
        this.decoratorService = Mockito.mock(DecoratorService.class);

        // Class tested
        this.myClass = new MyClass();
        this.myClass.setMyDecoratorService(decoratorService);
    }

    /**
     * Test the method named getLowerCase with a lowercase string.<br>
     * Must return a uppercase string
     */
    @Test
    public void getLowerCase_LowerCaseStringGiven_ReturnUpperCase() {
        // GIVEN
        final String lowerText = "the lower text";
        final String decorateArgumentExpected = "THE LOWER TEXT";
        final String upperTextExpected = "[THE LOWER TEXT]";

        // Initialize the service mocked
        ArgumentCaptor<String> txtDecorateCaptor = ArgumentCaptor.forClass(String.class);
        Mockito.when(decoratorService.decorate(txtDecorateCaptor.capture()))
                .thenAnswer(x -> "[" + x.getArgument(0) + "]");
        // .thenReturn("Other static string result");

        // WHEN
        final String actionResult = this.myClass.toUpperCase(lowerText);

        // THEN
        Assertions.assertEquals(upperTextExpected, actionResult);
        // Check service mock called 1 time
        Mockito.verify(decoratorService, Mockito.times(1)).decorate(Mockito.anyString());
        // Test service mock argument value
        Assertions.assertEquals(decorateArgumentExpected, txtDecorateCaptor.getValue());
    }
}

LauLem.com - Conditions Générales d'Utilisation - Informations Légales - Charte relative aux cookies - Charte sur la protection des données personnelles - A propos