Annotations additionnelles

Introduction aux tests en Java

Maria Milusheva

Senior Software Engineer

Préalable : création d'objets avec .of()

Considérez :

List<Integer> newList = new ArrayList<Integer>();
newList.add(10);
newList.add(20);
newList.add(30);

Façon plus rapide et plus courte :

List<Integer> newList = List.of(10, 20, 30);
  • Fonctionne pareil pour Set et Map des Java Collections

  • Les objets créés avec .of() sont généralement immuables (ne changent pas)

Introduction aux tests en Java

Passer des objets à @ParameterizedTest

Considérez la classe suivante :

class Person {
    String firstName;
    String lastName;
    public Person(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }
    public String fullName(Person person) {
        return firstName + " " + lastName;
    }
}
Introduction aux tests en Java

Classe Arguments

On utilise Arguments pour passer plusieurs paramètres de tout type.

Arguments : peut contenir n'importe quel nombre d'objets de toute sorte.

Par exemple :

Arguments.of(new Person("Monty", "Python"), "Monty Python");

On peut maintenant l'utiliser dans le type @ParameterizedTest suivant.

Introduction aux tests en Java

@MethodSource

@MethodSource permet de passer n'importe quel objet à un test.

Le test ressemble à :

@ParameterizedTest
@MethodSource("provideNames")
void testFullName(Person person, String expectedFullName) {
    assertEquals(person.fullName(person), expectedFullName);
}
Introduction aux tests en Java

Méthode fournisseuse @MethodSource

Méthode pour @MethodSource :

private static List<Arguments> provideNames() {
    List<Arguments> args = new ArrayList<>();
    args.add(Arguments.of(new Person("Robert", "Martin"), "Robert Martin"));
    args.add(Arguments.of(new Person("Heinz", "Kabutz"), "Heinz Kabutz"));

    return args;
}

Remarque : la méthode doit être static

Remarque : plusieurs types de retour permis ; List<Arguments> est le plus simple

1 https://junit.org/junit5/docs/5.2.0/api/org/junit/jupiter/params/provider/MethodSource.html
Introduction aux tests en Java

Méthode fournisseuse @MethodSource

Méthode pour @MethodSource :

private static List<Arguments> provideNames() {
    return List.of(
        Arguments.of(new Person("John", "Doe"), "John Doe"),
        Arguments.of(new Person("Jane", "Doe"), "Jane Doe"),
        Arguments.of(new Person("Alice", "Bob"), "Alice Bob"));
}
Introduction aux tests en Java

Et si nous avons besoin de plus que des arguments ?

Considérez le test de bases de données :

@Test
void process_savesToInfoStore_whenInfoMessage() {
  InfoStore infoStore = mock(InfoStore.class);
  ErrorStore errorStore = mock(ErrorStore.class);
  MessageProcessor messageProcessor = new MessageProcessor(infoStore, errorStore);

messageProcessor.saveMessage("[INFO] Process started.");
verify(infoStore).save("[INFO] Process started."); verifyNoInteractions(errorStore); }
Introduction aux tests en Java

Annotation @BeforeEach

On peut utiliser l'annotation @BeforeEach pour créer une méthode exécutée avant chaque test :

import org.junit.jupiter.api.BeforeEach;

Pour l'utiliser, déclarez d'abord les objets comme champs :

class MessageProcessorTest {

    private InfoStore infoStore;
    private ErrorStore errorStore;
    private MessageProcessor messageProcessor;
Introduction aux tests en Java

Méthode pour @BeforeEach

Créez chaque objet dans une méthode distincte :

@BeforeEach
void setUp() {
    this.infoStore = mock(InfoStore.class);
    this.errorStore = mock(errorStore.class);
    this.messageProcessor = new MessageProcessor(infoStore, errorStore);
}
Introduction aux tests en Java

Test raccourci

La classe de test devient alors :

@Test
void process_savesToInfoStore_whenInfoMessage() {
    messageProcessor.process("[INFO] Process started.");

    verify(infoStore).save("[INFO] Process started."); 
    verifyNoInteractions(errorStore); 
}
Introduction aux tests en Java

Enchaînement complet @BeforeEach

Ensemble :

class MessageProcessorTest {
    private InfoStore infoStore; // Déclarer les champs


@BeforeEach void setUp() { this.infoStore = mock(InfoStore.class); // Initialiser les champs }
@Test void process_savesToInfoStore_whenInfoMessage() { // Utiliser les champs } }
Introduction aux tests en Java

Passons à la pratique !

Introduction aux tests en Java

Preparing Video For Download...