Introduzione al Testing in Java
Maria Milusheva
Senior Software Engineer
Ricorda l’esercizio di validazione dello username del Capitolo 1:
public static boolean isValidUsername(String username) {
if (username == null || username.isEmpty() || username.contains(" ")) {
return false;
}
return username.length() >= 3;
}
Ricorda che i test erano così:
@Test
void isValidUsername_returnsFalse() {
String username = "____";
boolean actual = isValidUsername(username);
assertFalse(actual);
}
Non serve scriverne 3!
Invece di @Test, usiamo @ParameterizedTest.
Si importa da:
import org.junit.jupiter.params.ParameterizedTest;
Serve anche un’altra annotazione: @ValueSource.
Si importa da:
import org.junit.jupiter.params.provider.ValueSource;
@ParameterizedTest
@ValueSource(strings = {"", "jane doe"}) // NOTA: è "strings", non String
void isValidUsername_returnsFalse(String username) { // I test possono accettare argomenti
boolean actual = isValidUsername(username);
assertFalse(actual);
}
Junit lo esegue come due test:
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
All tests passed!
@ValueSource è limitato a certi tipi.
@ValueSource(bytes = {1, 2, 3, 42})
@ValueSource(shorts = {100, 200, 300})
@ValueSource(ints = {1, 2, 3, 42})
@ValueSource(longs = {1000L, 2000L, 3000L})
@ValueSource(floats = {1.0f, 3.14159f, 2.71828f})
@ValueSource(doubles = {3.14, 2.71828, 1.4142})
@ValueSource(chars = {'a', 'b', 'c', 'Z'})
@ValueSource(booleans = {true, false})
@ValueSource(strings = {"Hello", "JUnit", "5", "Parameter"})
@ValueSource(classes = {String.class, Integer.class, ValueSourceExamples.class})
Non possiamo passare null a @ValueSource: non compila.
@ParameterizedTest
@ValueSource(strings = {"", "jane doe", null}) // Non compila
void isValidUsername_returnsFalse(String username) {
boolean actual = isValidUsername(username);
assertFalse(actual);
}
Usa invece @NullSource.
Se passiamo null a @ValueSource, non compila.
@ParameterizedTest
@NullSource // Aggiunge un caso di test con null
@ValueSource(strings = {"", "jane doe"})
void isValidUsername_returnsFalse(String username) {
boolean actual = isValidUsername(username);
assertFalse(actual);
}
Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
All tests passed!
Altro limite di @ValueSource: può passare un solo valore per test.
Considera questo metodo:
int countLetters(String input) {
if (input != null) {
return input.length();
}
return 0;
}
Per valori multipli, usa @CsvSource (CSV = comma-separated values):
@ParameterizedTest
@CsvSource({"Hello World, 11", "DataCamp, 8", "'', 0", ", 0"})
void countLetters_countsLetters(String input, int expected) {
int actual = countLetters(input);
assertEquals(expected, actual);
}
Nota che ", 0" inserisce null, 0. Per una stringa vuota, usa "'', 0" in JUnit 5.10
@CsvSource has similar type limitations as @ValueSource.
Tutte le annotazioni @____Source si importano da:
import org.junit.jupiter.params.provider.*;
Introduzione al Testing in Java