Úvod do testování v Javě
Maria Milusheva
Senior Software Engineer
Uvažujme cvičení na ověření uživatelského jména z kapitoly 1:
public static boolean isValidUsername(String username) {
if (username == null || username.isEmpty() || username.contains(" ")) {
return false;
}
return username.length() >= 3;
}
Připomeňme, že testy vypadaly takto:
@Test
void isValidUsername_returnsFalse() {
String username = "____";
boolean actual = isValidUsername(username);
assertFalse(actual);
}
Nemusíme psát 3 takové testy!
Místo @Test používáme @ParameterizedTest
Importujeme z:
import org.junit.jupiter.params.ParameterizedTest;
Dále potřebujeme anotaci @ValueSource.
Importujeme z:
import org.junit.jupiter.params.provider.ValueSource;
@ParameterizedTest
@ValueSource(strings = {"", "jane doe"}) // NOTE: It's "strings", not String
void isValidUsername_returnsFalse(String username) { // Tests can take arugments
boolean actual = isValidUsername(username);
assertFalse(actual);
}
JUnit spustí tento test dvakrát:
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
All tests passed!
@ValueSource je omezeno na určité typy.
@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})
Předání null do @ValueSource způsobí chybu kompilace:
@ParameterizedTest
@ValueSource(strings = {"", "jane doe", null}) // Does not compile
void isValidUsername_returnsFalse(String username) {
boolean actual = isValidUsername(username);
assertFalse(actual);
}
Místo toho použijte @NullSource.
Pokud předáme null do @ValueSource, kód se nezkompiluje.
@ParameterizedTest
@NullSource // Adds a null input test case
@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!
Další omezení @ValueSource – lze předat pouze jednu hodnotu na test.
Uvažujme následující metodu:
int countLetters(String input) {
if (input != null) {
return input.length();
}
return 0;
}
Pro více hodnot použijte @CsvSource (CSV = hodnoty oddělené čárkou):
@ParameterizedTest
@CsvSource({"Hello World, 11", "DataCamp, 8", "'', 0", ", 0"})
void countLetters_countsLetters(String input, int expected) {
int actual = countLetters(input);
assertEquals(expected, actual);
}
Poznámka: ", 0" je předáno jako null, 0. Pro prázdný řetězec použijte "'', 0" v JUnit 5.10
@CsvSource has similar type limitations as @ValueSource.
Všechny anotace @____Source lze importovat z:
import org.junit.jupiter.params.provider.*;
Úvod do testování v Javě