Bắt đầu ngayBắt đầu miễn phí

Unit test: Cơ sở dữ liệu với danh sách

Xét ErrorStoreInfoStore trong bài học, nhưng giờ phương thức process() của chúng ta nhận vào một danh sách thông điệp. Với danh sách đầu vào đã cho, hãy kiểm tra mỗi cơ sở dữ liệu được gọi đúng số lần.

Bài tập này là một phần của khóa học

Nhập môn Kiểm thử trong Java

Xem khóa học

Hướng dẫn bài tập

  • Tạo một mock cho InfoStore.
  • Tạo một mock cho ErrorStore.
  • Xác minh InfoStore mock được gọi bao nhiêu lần với các đối số hiện tại.
  • Xác minh ErrorStore mock được gọi bao nhiêu lần với các đối số hiện tại.

Bài tập tương tác thực hành trực tiếp

Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.

public class Main {
    public static void main(String[] args) {
		launchMockitoTestsAndPrint(MessageProcessorTest.class);
    }
}

class MessageProcessorTest {
    @Test
    void process_savesToCorrectDatabase_whenValidInputList() {
        List sampleMessages = new ArrayList<>();
        sampleMessages.add("[INFO] An info message.");
        sampleMessages.add("[INFO] An info message.");
        sampleMessages.add("[ERROR] An error message.");
        sampleMessages.add("[INFO] An info message.");
        
    	// Create a mock for the InfoStore
        InfoStore ____ = ____(____.class);
        // Create a mock for the ErrorStore
        ErrorStore ____ = ____(____.class);
        MessageProcessor processor = new MessageProcessor(infoStore, errorStore);
        processor.process(sampleMessages);

		// Verify how many times the infoStore has to store the message
        ____(____, times(3)).save("[INFO] An info message.");
        // Verify how many times the errorStore has to store the message
        ____(____, times(1)).save("[ERROR] An error message."); 
    }
}
Chỉnh sửa và Chạy Mã