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) :


    17
    17
    17

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



    org.mockito
    mockito-core
    3.3.3
    test

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


    org.junit.jupiter
    junit-jupiter-engine
    5.4.0
    test

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 :


	org.apache.maven.plugins
	maven-surefire-plugin
	
	2.22.2

Fichier pom.xml complet :


    4.0.0
    GROUP_ID
    ARTIFACT_ID
    0.0.1-SNAPSHOT

    
        17
        17
        17
    

    
        
            org.mockito
            mockito-core
            3.3.3
            test
        
        
            org.junit.jupiter
            junit-jupiter-engine
            5.9.1
            test
        
    

    
        
            
                org.apache.maven.plugins
                maven-surefire-plugin
                
                2.22.2
            
        
    

 

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