Mặc định, JUnit chạy test theo thứ tự không thể dự đoán. Có lúc bạn muốn chạy test theo một thứ tự cụ thể.
Ví dụ, tưởng tượng kịch bản bạn đang test một user management API. Các kịch bản sẽ theo thứ tự cụ thể này:
- 1 - Test tạo user
- 2 - Test cập nhật user
- 3 - Test xóa user
Để cập nhật hoặc xóa user, chúng ta cần trước tiên tạo user.
Trong JUnit 5, chúng ta có thể dùng annotation @TestMethodOrder và @Order để chạy test theo thứ tự.
Chạy Test Theo Thứ Tự
Ví dụ:
import org.junit.jupiter.api.*;
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class TestOrder {
@Test
@Order(1)
public void testCreateUser() {
// code to test user creation
}
@Test
@Order(2)
public void testUpdateUser() {
// code to test user update
}
@Test
@Order(3)
public void testDeleteUser() {
// code to test user deletion
}
}
Với các annotation trên, các test sẽ chạy theo thứ tự chỉ định.