單元測試:使用清單的資料庫
回想課程中的 ErrorStore 與 InfoStore,但現在 process() 方法會接收一個訊息清單。根據提供的輸入清單,驗證每個資料庫被呼叫的次數是否正確。
本練習屬於課程
Java 測試入門
練習說明
- 為
InfoStore建立一個 mock。 - 為
ErrorStore建立一個 mock。 - 驗證在目前的引數下,
InfoStore的 mock 被呼叫的次數。 - 驗證在目前的引數下,
ErrorStore的 mock 被呼叫的次數。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
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.");
}
}