始める無料で始める

ユニットテスト:リストを使うデータベース

レッスンで登場した ErrorStoreInfoStore を考えます。ここでは、process() メソッドがメッセージのリストを受け取ります。与えられた入力リストに対して、各データベースが正しい回数だけ呼び出されていることを検証してください。

この演習はコースの一部です

Javaによるテスト入門

コースを見る

演習の手順

  • InfoStore のモックを作成します。
  • ErrorStore のモックを作成します。
  • 現在の引数で InfoStore のモックが何回呼び出されるかを検証します。
  • 現在の引数で 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."); 
    }
}
コードを編集して実行