Unit test: Basis data dengan daftar
Pertimbangkan ErrorStore dan InfoStore dari pelajaran, tetapi kini metode process() menerima sebuah daftar pesan. Dengan daftar masukan yang diberikan, verifikasi bahwa setiap basis data dipanggil dengan jumlah yang benar.
Latihan ini adalah bagian dari kursus
Pengantar Pengujian di Java
Petunjuk latihan
- Buat mock untuk
InfoStore. - Buat mock untuk
ErrorStore. - Verifikasi berapa kali mock
InfoStoreakan dipanggil dengan argumen saat ini. - Verifikasi berapa kali mock
ErrorStoreakan dipanggil dengan argumen saat ini.
Latihan interaktif praktis
Cobalah latihan ini dengan menyelesaikan kode contoh berikut.
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.");
}
}