始める無料で始める

ユニットテスト:アラート

ソフトウェアエンジニアリングでは、処理に時間がかかりすぎたときにアラートを発することで、コードが十分に速く動作しているかを確認することがよくあります。ここでは、AlertService に依存する DurationMonitor というクラスが与えられています。1秒(1000ミリ秒 = 1秒)を超える時間が渡されると、AlertService 上でアラートを発します。

長い時間に対しては実際にアラートが発生し、1秒未満の時間ではアラートが発生しないことを検証してください。

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

Javaによるテスト入門

コースを見る

演習の手順

  • 長い時間の場合に alertService のモックが呼び出されることを検証してください。
  • 例の長い時間で、alertService のどのメソッドがどんな引数で呼ばれるかを検証してください。
  • 2つ目のテストでは、alertService が呼び出されないことを検証してください。

実践的なインタラクティブ演習

このサンプルコードを完成させて、この演習に挑戦してみましょう。

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

class DurationMonitorTest {

    @Test
    void recordDuration_triggersAlert_whenAboveLimit() {
        AlertService alertService = mock(AlertService.class);
        DurationMonitor monitor = new DurationMonitor(alertService);
        monitor.recordDuration(1500);

        // Verify alertService.trigger() was called with the expected message
        ____(alertService).____("Slow execution detected: 1500ms");
    }

    @Test
    void recordDuration_doesNotTriggerAlert_whenUnderLimit() {
        AlertService alertService = mock(AlertService.class);
        DurationMonitor monitor = new DurationMonitor(alertService);
        monitor.recordDuration(500);

        // Verify alertService was not used
        ____(____);
    }
}
コードを編集して実行