開始使用免費開始

單元測試:資料庫訊息

回想課程中的 ErrorStoreInfoStore。假設對一則 [WARN] 訊息呼叫 process(String message) 方法,代表它不會進到任一個資料庫。請撰寫測試來驗證這件事。

本練習屬於課程

Java 測試入門

檢視課程

練習說明

  • 驗證該訊息沒有被存到 infoStore
  • 使用 times() 的驗證方式,確認它也沒有被存到 errorStore
  • 在同一個敘述中,加入未被呼叫的資料庫方法 save()

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

public class Main {
    public static void main(String[] args) {
        launchMockitoTestsAndPrint(MessageProcessorTest.class);
    }
}

class MessageProcessorTest {

    @Test
    void process_savesNowhere_whenWrongMessageType() {
        InfoStore infoStore = mock(InfoStore.class);
        ErrorStore errorStore = mock(ErrorStore.class);
        MessageProcessor processor = new MessageProcessor(infoStore, errorStore);
        String message = "[WARN] The search is slow.";

        processor.process(message);

        // Verify infoStore was not called
        ____(infoStore);
        // Verify errorStore.save was called 0 times
        verify(errorStore, ____(0)).____(message);
    }
}
編輯並執行程式碼