BeforeEach: アラート処理
プロジェクトが複雑になるにつれて、テストのセットアップはどんどん長くなることがあります。これを見越して、DurationMonitorTest を見直し、新しいアノテーションを使って一部のセットアップを setup() メソッドに切り出します。
@BeforeEach を使って、各テストの前にセットアップが実行されるようにしましょう。
この演習はコースの一部です
Javaによるテスト入門
演習の手順
setup()メソッドに正しいアノテーションを付けてください。- 必要なセットアップを書きましょう。
AlertServiceはモックにし、DurationMonitorにはそのモックを渡します。
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
public class Main {
public static void main(String[] args) {
launchMockitoTestsAndPrint(DurationMonitorTest.class);
}
}
class DurationMonitorTest {
private AlertService alertService;
private DurationMonitor monitor;
// Use the correct annotation to make this method execute before every test
@____
void setUp() {
// Set up the mock alertService and the monitor as you did in the earlier exercise
this.alertService = ____(____.class);
this.monitor = new ____(alertService);
}
@Test
void recordDuration_triggersAlert_whenAboveLimit() {
this.monitor.recordDuration(1500);
verify(this.alertService).trigger("Slow execution detected: 1500ms");
}
@Test
void recordDuration_doesNotTriggerAlert_whenUnderLimit() {
this.monitor.recordDuration(500);
verifyNoInteractions(this.alertService);
}
}