การทดสอบใน Java เบื้องต้น
Maria Milusheva
Senior Software Engineer
ลองนึกถึงแบบฝึกหัดการตรวจสอบชื่อผู้ใช้จากบทที่ 1:
public static boolean isValidUsername(String username) {
if (username == null || username.isEmpty() || username.contains(" ")) {
return false;
}
return username.length() >= 3;
}
ทบทวนว่าการทดสอบมีลักษณะดังนี้:
@Test
void isValidUsername_returnsFalse() {
String username = "____";
boolean actual = isValidUsername(username);
assertFalse(actual);
}
ไม่จำเป็นต้องเขียนการทดสอบแบบนี้ถึง 3 ครั้ง!
แทนที่ @Test ให้ใช้ @ParameterizedTest
นำเข้าจาก:
import org.junit.jupiter.params.ParameterizedTest;
ยังต้องใช้ annotation เพิ่มอีกหนึ่งตัวคือ @ValueSource.
นำเข้าจาก:
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 รันนี้เป็นสองการทดสอบ:
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
All tests passed!
@ValueSource รองรับเฉพาะบางประเภทข้อมูล
@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})
ไม่สามารถส่ง null ให้ @ValueSource ได้ เพราะจะคอมไพล์ไม่ผ่าน:
@ParameterizedTest
@ValueSource(strings = {"", "jane doe", null}) // Does not compile
void isValidUsername_returnsFalse(String username) {
boolean actual = isValidUsername(username);
assertFalse(actual);
}
ให้ใช้ @NullSource แทน
การส่ง null ให้ @ValueSource จะทำให้คอมไพล์ไม่ผ่าน
@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!
ข้อจำกัดอีกประการของ @ValueSource คือส่งได้เพียงหนึ่งค่าต่อการทดสอบ
พิจารณาเมธอดต่อไปนี้:
int countLetters(String input) {
if (input != null) {
return input.length();
}
return 0;
}
สำหรับหลายค่า ให้ใช้ @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);
}
หมายเหตุ: ", 0" จะถูกรับเป็น null, 0 หากต้องการส่งสตริงว่าง ให้ใช้ "'', 0" ใน JUnit 5.10
@CsvSource has similar type limitations as @ValueSource.
สามารถนำเข้า annotation @____Source ทั้งหมดได้จาก:
import org.junit.jupiter.params.provider.*;
การทดสอบใน Java เบื้องต้น