Nhập môn Kiểm thử trong Java
Maria Milusheva
Senior Software Engineer
Xét lại bài tập kiểm tra tên người dùng ở Chương 1:
public static boolean isValidUsername(String username) {
if (username == null || username.isEmpty() || username.contains(" ")) {
return false;
}
return username.length() >= 3;
}
Hãy nhớ các bài kiểm thử trông như sau:
@Test
void isValidUsername_returnsFalse() {
String username = "____";
boolean actual = isValidUsername(username);
assertFalse(actual);
}
Chúng ta không cần viết 3 bài kiểm thử như vậy!
Thay vì @Test, dùng @ParameterizedTest
Được import từ:
import org.junit.jupiter.params.ParameterizedTest;
Cũng cần thêm annotation: @ValueSource.
Được import từ:
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 chạy như hai bài kiểm thử:
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
All tests passed!
@ValueSource chỉ hỗ trợ một số kiểu nhất định.
@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})
Không thể truyền null vào @ValueSource vì sẽ không biên dịch:
@ParameterizedTest
@ValueSource(strings = {"", "jane doe", null}) // Does not compile
void isValidUsername_returnsFalse(String username) {
boolean actual = isValidUsername(username);
assertFalse(actual);
}
Thay vào đó dùng @NullSource.
Nếu truyền null vào @ValueSource, mã sẽ không biên dịch.
@ParameterizedTest
@NullSource // Thêm ca kiểm thử đầu vào 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!
Một giới hạn khác của @ValueSource – chỉ truyền được một giá trị mỗi test.
Xét phương thức sau:
int countLetters(String input) {
if (input != null) {
return input.length();
}
return 0;
}
Với nhiều giá trị, dùng @CsvSource (CSV = giá trị phân tách bằng dấu phẩy):
@ParameterizedTest
@CsvSource({"Hello World, 11", "DataCamp, 8", "'', 0", ", 0"})
void countLetters_countsLetters(String input, int expected) {
int actual = countLetters(input);
assertEquals(expected, actual);
}
Lưu ý ", 0" được nhập là null, 0. Để nhập chuỗi rỗng, dùng "'', 0" trong JUnit 5.10
@CsvSource has similar type limitations as @ValueSource.
Tất cả các annotation @____Source có thể import từ:
import org.junit.jupiter.params.provider.*;
Nhập môn Kiểm thử trong Java