Unit test: Thông điệp vào cơ sở dữ liệu
Xem lại ErrorStore và InfoStore trong bài học. Giả sử phương thức process(String message) được dùng cho một thông điệp [WARN], nghĩa là nó sẽ không đi vào bất kỳ cơ sở dữ liệu nào. Viết một bài test để kiểm chứng điều đó.
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
Hướng dẫn bài tập
- Xác minh thông điệp không đi vào
infoStore. - Xác minh nó cũng không đi vào
errorStorebằng cách dùng cách verify vớitimes(). - Trong cùng câu lệnh đó, thêm phương thức của cơ sở dữ liệu,
save(), vốn đã không được gọ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_savesNowhere_whenWrongMessageType() {
InfoStore infoStore = mock(InfoStore.class);
ErrorStore errorStore = mock(ErrorStore.class);
MessageProcessor processor = new MessageProcessor(infoStore, errorStore);
String message = "[WARN] The search is slow.";
processor.process(message);
// Verify infoStore was not called
____(infoStore);
// Verify errorStore.save was called 0 times
verify(errorStore, ____(0)).____(message);
}
}