单元测试:数据库消息
回想课程中的 ErrorStore 和 InfoStore。假设对一个 [WARN] 消息调用了 process(String message) 方法,这意味着它不会进入任一数据库。请编写一个测试来验证这一点。
本练习是课程的一部分
Java 测试入门
练习说明
- 验证该消息没有进入
infoStore。 - 使用
times()的验证方式,再验证它也没有进入errorStore。 - 在同一条语句中,添加未被调用的数据库方法
save()。
交互式实操练习
通过完成这段示例代码来试试这个练习。
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);
}
}