開始使用免費開始

單元測試:使用清單的資料庫

回想課程中的 ErrorStoreInfoStore,但現在 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."); 
    }
}
編輯並執行程式碼