Tags:

Sử dụng @BeforeAll và @AfterAll mà không cần static method

Mặc định, @BeforeAll và @AfterAll annotation trong Junit 5 phải được dùng với static method, tuy nhiên nếu các bạn muốn sử dụng 2 annotation này trên instance method thì chúng ta sẽ cùng nhau tìm hiểu trong bài viết này.

Khi triển khai unit-test 2 annotation @BeforeAll được dùng để chuẩn bị một số dữ liệu, cấu hình ban đầu cần cho quá trình chạy các test-method trong một class, @AfterAll lại được dùng để dọn dẹp những dữ liệu dư thừa trong quá trình chạy unit-test tạo ra.

Giả sử như chúng ta có một unit-test như sau

@ExtendWith(MockitoExtension.class)
public class BeforeAndAfterAnnotationsUnitTest {

    String input;
    Long result;

    @BeforeAll
    public void setup() {
        input = "77";
    }

    @AfterAll
    public void teardown() {
        input = null;
        result = null;
    }

    @Test
    public void whenConvertStringToLong_thenResultShouldBeLong() {
        result = Long.valueOf(input);
        Assertions.assertEquals(77l, result);
    }​
}

Nếu chạy kiểm thử BeforeAndAfterAnnotationsUnitTest thì chúng ta sẽ nhận được lỗi sau

org.junit.platform.commons.JUnitException:  ...

Để khắc phục lỗi này, chúng ta cần sử dụng @TestInstance kết hợp với tham số TestInstance.Lifecycle.PER_CLASS. @TestInstance annotation được dùng để cấu hình vòng đời của một test-class, mặc định sẽ là PER_METHOD. Như vậy chúng ta chỉ cần chuyển sang PER_CLASS thì có thể sử dụng @BeforeAll và @AfterAll với một instance method thông thường.

@ExtendWith(MockitoExtension.class)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class BeforeAndAfterAnnotationsUnitTest {

    String input;
    Long result;

    @BeforeAll
    public void setup() {
        input = "77";
    }

    @AfterAll
    public void teardown() {
        input = null;
        result = null;
    }

    @Test
    public void whenConvertStringToLong_thenResultShouldBeLong() {
        result = Long.valueOf(input);
        Assertions.assertEquals(77l, result);
    }
}

Tóm lược

Qua bài viết ngắn này chúng ta đã biết được cách sử dụng @BeforeAll và @AfterAll với instance method thông thường thay vì phải sử dụng với static method trước đây sẽ gây ra một số khó khăn nhất định trong quá trình triển khai unit-test.

Nguồn: baeldung

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x