Unit test: ฐานข้อมูลกับลิสต์ข้อความ
ลองพิจารณา ErrorStore และ InfoStore จากบทเรียน แต่คราวนี้ method process() รับลิสต์ของข้อความเป็นอาร์กิวเมนต์ จากลิสต์ที่กำหนดให้ ให้ตรวจสอบว่าแต่ละฐานข้อมูลถูกเรียกใช้กี่ครั้ง
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
การทดสอบใน Java เบื้องต้น
คำแนะนำการฝึกหัด
- สร้าง mock สำหรับ
InfoStore - สร้าง mock สำหรับ
ErrorStore - ตรวจสอบว่า mock ของ
InfoStoreจะถูกเรียกกี่ครั้งด้วยอาร์กิวเมนต์ที่กำหนด - ตรวจสอบว่า mock ของ
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.");
}
}