单元测试:包含列表的数据库
回顾课程中的 ErrorStore 和 InfoStore,不过现在我们的 process() 方法接收的是一个消息列表。根据给定的输入列表,验证每个数据库被调用的次数是否正确。
本练习是课程的一部分
Java 测试入门
练习说明
- 为
InfoStore创建一个模拟对象。 - 为
ErrorStore创建一个模拟对象。 - 验证在当前参数下,
InfoStore的模拟对象被调用了多少次。 - 验证在当前参数下,
ErrorStore的模拟对象被调用了多少次。
交互式实操练习
通过完成这段示例代码来试试这个练习。
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.");
}
}