申請の締切の直前・ちょうど・直後を時計で検証する記事のアイキャッチ

実装・エラー解決

Spring Bootのテストで時刻を固定する|ClockをDIして締切を確かめる

社内申請の受付状況を返すAPIで、締切ちょうどから受付終了にします。前日に書いたテストは通ったのに、締切を過ぎて同じテストを実行すると結果が変わりました。アプリが実際の現在時刻を使っていると、テストを実行するたびに「締切の前に試しているか」が変わります。

判定するクラスへ Clock を渡し、本番ではシステム時計、テストでは固定した時計をSpringに選ばせます。同じ締切を使い、時計だけを変えて直前・ちょうど・直後のHTTP応答を比べます。

この記事でわかること

  • 本番の Clock をBeanとして登録し、Serviceへ渡す方法
  • @TestConfiguration と @Primary で、テストにだけ固定した時計を渡す方法
  • 締切を変えず、MockMvcで直前・ちょうど・直後を検証する方法

記事と同じコードを実行する

ZIPを展開し、JDK 17とMaven 3.9系で mvn test を実行します。Spring Boot本体、締切の設定、Clockのテスト設定、MockMvcのテスト、pom.xml、READMEを収録しています。

サンプルZIPをダウンロード GitHubでコード全文と実行手順を見る

締切ちょうどに受付を終了し、状態照会は200を返す

GET /application-window は、現在受け付けているかを accepting、締切の瞬間を closesAt で返します。締切は 2026-11-20T08:00:00Z です。締切より前は true、同じ瞬間から false。このGETは受付可否を問い合わせるため、受付が終了していても照会自体はHTTP 200です。

時計だけを動かし、同じ締切の3点で確かめる

締切は 。

  1. 1ナノ秒前受付可能accepting: true
  2. 締切ちょうど受付終了accepting: false
  3. 1ナノ秒後受付終了accepting: false

テストが変えるのは、現在時刻として読む値です。締切時刻やHTTPの応答形式を変更すると、締切ちょうどの仕様を本番と同じ条件で確かめられません。時刻の比較は Instant で行い、画面で日本時間を表示する要件があれば、同じ瞬間を表示時に変換します。

本番ではClock.systemUTCをBeanにして、Serviceで現在時刻を読む

Serviceに Instant.now() を直接書くと、テストからその呼び出しの結果だけを指定できません。コンストラクターで Clock を受け取り、clock.instant() で読む形にすると、締切の計算は同じまま、時刻の供給元を選べます。JavaだけでClockを渡して判定を確かめる手順も参照できます。

関連記事Javaの現在日時をテストで固定する方法|Clock.fixedで期限判定を確認する Springを使わず、ClockをJavaクラスへ渡して、現在日時に依存する判定をテストするところから確認できます。 記事を読む

ApplicationWindowApp.java(全文)

package info.syachiku.window;

import java.time.Clock;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication(proxyBeanMethods = false)
public class ApplicationWindowApp {
    public static void main(String[] args) {
        SpringApplication.run(ApplicationWindowApp.class, args);
    }

    @Bean
    Clock applicationClock() {
        return Clock.systemUTC();
    }
}

アプリ起動クラスの applicationClock() が本番の時計を作ります。Clock.systemUTC() は現在の瞬間をシステム時計から読み、タイムゾーンにはUTCを使うClockです。テストでも同じ ApplicationWindow を使います。Java 17のClockのAPIで、システム時計と固定時計の役割を確認できます。

ApplicationWindow.java(全文)

package info.syachiku.window;

import java.time.Clock;
import java.time.Instant;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class ApplicationWindow {
    private final Clock clock;
    private final Instant closesAt;

    public ApplicationWindow(Clock clock, @Value("${application.closes-at}") String closesAt) {
        this.clock = clock;
        this.closesAt = Instant.parse(closesAt);
    }

    public Status status() {
        return new Status(clock.instant().isBefore(closesAt), closesAt);
    }

    public record Status(boolean accepting, Instant closesAt) {
    }
}

締切は application.properties から取得し、Instant.parse で日時に変換します。isBefore は同じ瞬間に false を返すため、「締切ちょうどから終了」という仕様になります。ControllerはServiceの結果を返し、現在時刻を別に読み直しません。

application.properties(全文)
application.closes-at=2026-11-20T08:00:00Z
ApplicationWindowController.java(全文)
package info.syachiku.window;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ApplicationWindowController {
    private final ApplicationWindow window;

    public ApplicationWindowController(ApplicationWindow window) {
        this.window = window;
    }

    @GetMapping("/application-window")
    public ApplicationWindow.Status status() {
        return window.status();
    }
}

テスト専用の固定Clockを別名で登録し、@Primaryで選ぶ

FixedClockConfiguration.java(全文)

package info.syachiku.window;

import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;

@TestConfiguration(proxyBeanMethods = false)
class FixedClockConfiguration {
    @Bean
    @Primary
    Clock fixedTestClock(@Value("${test.clock.instant}") String now) {
        return Clock.fixed(Instant.parse(now), ZoneOffset.UTC);
    }
}

FixedClockConfiguration は src/test/java に置き、必要なテストに @Import(FixedClockConfiguration.class) を書きます。@TestConfiguration はテストに追加する設定です。このサンプルではトップレベルのクラスとして定義し、明示的に取り込みます。Spring Boot 3.5のテスト設定資料でも、この方法が説明されています。

本番のBean名は applicationClock、テストは fixedTestClock です。テストのコンテキストには二つのBeanがあり、@Primary が、Serviceのように名前を指定せず一つの Clock を受け取る場所で固定時計を優先させます。既存Beanを同じ名前で上書きする設定は使いません。@Qualifier で本番Bean名を指定しているコードは、その指定も確認します。Spring Frameworkの@Primaryの説明に、単一の依存先を選ぶ扱いがあります。

固定時計の時刻はテストごとの test.clock.instant から取得します。これを変えると固定Clockだけが変わり、application.closes-at は共通のままです。JVMの時計やデフォルトのタイムゾーンを変更する必要はありません。

同じ締切を使い、MockMvcで3つの時刻のJSONを比べる

直前・ちょうど・直後を三つのテストクラスに分け、それぞれ @TestPropertySource で固定する時刻を指定します。各クラスは @SpringBootTest と @AutoConfigureMockMvc でアプリの設定を読み、同じURLにGETします。accepting の値と一緒に、すべてのケースで closesAt が同じ文字列であることを確認します。Spring FrameworkのMockMvc資料にあるように、テストでは実際のサーバーのポートを開かず、MVCのリクエスト処理を通します。

BeforeDeadlineTest.java(全文)
package info.syachiku.window;

import java.time.Clock;
import java.time.Instant;
import java.util.Set;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.web.servlet.MockMvc;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@SpringBootTest
@AutoConfigureMockMvc
@Import(FixedClockConfiguration.class)
@TestPropertySource(properties = "test.clock.instant=2026-11-20T07:59:59.999999999Z")
class BeforeDeadlineTest {
    @Test
    void acceptsOneNanosecondBefore(@Autowired MockMvc mvc) throws Exception {
        mvc.perform(get("/application-window"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.accepting").value(true))
                .andExpect(jsonPath("$.closesAt").value("2026-11-20T08:00:00Z"));
    }

    @Test
    void fixedClockIsPrimaryAndProductionBeanKeepsItsName(@Autowired ApplicationContext context) {
        assertEquals(Set.of("applicationClock", "fixedTestClock"),
                context.getBeansOfType(Clock.class).keySet());
        Clock fixed = context.getBean("fixedTestClock", Clock.class);
        assertSame(fixed, context.getBean(Clock.class));
        assertEquals(Instant.parse("2026-11-20T07:59:59.999999999Z"), fixed.instant());
    }
}
AtDeadlineTest.java(全文)
package info.syachiku.window;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.web.servlet.MockMvc;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@SpringBootTest
@AutoConfigureMockMvc
@Import(FixedClockConfiguration.class)
@TestPropertySource(properties = "test.clock.instant=2026-11-20T08:00:00Z")
class AtDeadlineTest {
    @Test
    void rejectsAtDeadline(@Autowired MockMvc mvc) throws Exception {
        mvc.perform(get("/application-window"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.accepting").value(false))
                .andExpect(jsonPath("$.closesAt").value("2026-11-20T08:00:00Z"));
    }
}
AfterDeadlineTest.java(全文)
package info.syachiku.window;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.web.servlet.MockMvc;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@SpringBootTest
@AutoConfigureMockMvc
@Import(FixedClockConfiguration.class)
@TestPropertySource(properties = "test.clock.instant=2026-11-20T08:00:00.000000001Z")
class AfterDeadlineTest {
    @Test
    void rejectsOneNanosecondAfter(@Autowired MockMvc mvc) throws Exception {
        mvc.perform(get("/application-window"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.accepting").value(false))
                .andExpect(jsonPath("$.closesAt").value("2026-11-20T08:00:00Z"));
    }
}

直前のクラスには、二つのClockが別名で登録され、型から選ぶと固定時計になることを確かめるテストもあります。別の ProductionClockTest は固定時計の設定をインポートせず、本番側のBeanだけが見つかることとUTCを確認します。HTTPの3件と設定の2件で、計5件です。

ProductionClockTest.java(全文)
package info.syachiku.window;

import java.time.Clock;
import java.time.ZoneOffset;
import java.util.Set;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;

import static org.junit.jupiter.api.Assertions.assertEquals;

@SpringBootTest
class ProductionClockTest {
    @Test
    void applicationWithoutTheTestImportUsesOnlyTheUtcClock(@Autowired ApplicationContext context) {
        assertEquals(Set.of("applicationClock"), context.getBeansOfType(Clock.class).keySet());
        assertEquals(ZoneOffset.UTC, context.getBean(Clock.class).getZone());
    }
}
pom.xml(全文)
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>3.5.16</version>
    <relativePath/>
  </parent>
  <groupId>info.syachiku</groupId>
  <artifactId>spring-fixed-clock-test-sample</artifactId>
  <version>1.0.0</version>
  <properties>
    <java.version>17</java.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
      <exclusions>
        <exclusion>
          <groupId>org.mockito</groupId>
          <artifactId>mockito-core</artifactId>
        </exclusion>
        <exclusion>
          <groupId>org.mockito</groupId>
          <artifactId>mockito-junit-jupiter</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>
</project>

締切と同じ瞬間も許すと、ちょうどのテストだけが失敗する

ZIPを展開し、pom.xml のある場所で mvn test を実行すると5件成功します。別の場所へ展開し、ApplicationWindow.java の判定を !clock.instant().isAfter(closesAt) に変えます。「締切より後ではない」という条件には、締切と同じ瞬間も入ります。

通常実行と締切ちょうどを許す変異のログ抜粋

修正版の mvn test
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0

締切ちょうどを許す再現版の mvn test
[ERROR]   AtDeadlineTest.rejectsAtDeadline:24 JSON path "$.accepting" expected:<false> but was:<true>
[ERROR] Tests run: 5, Failures: 1, Errors: 0, Skipped: 0

この変更では、直前は引き続き true、直後は引き続き false です。同じ瞬間だけ false の期待に対して true が返ります。締切の前後だけを試すとこの誤りを検出できないため、仕様が切り替わる時刻そのものをテストに残します。確認後は isBefore に戻します。

レビューでは、締切・現在時刻・表示の担当を分けて読む

レビューコメント例「締切前と締切後のテストは通っています。08:00:00Zちょうどは受付終了の仕様なので、締切設定はそのままで、Clockを同時刻に固定するケースを足しましょう。200の応答に含まれる accepting がfalseかも確認してください。」

表示に日本時間を使う場合、2026-11-20T08:00:00Z は同じ日の17:00です。表示形式の変更と、受付終了の瞬間を変える変更を分けると、どちらのテストを直すべきか判断できます。この例で扱うのは状態を返すGETです。申請を登録する機能では、GETの結果だけで確定させず、登録時点の締切も別途確認します。

提出前に、固定時刻と締切ちょうどの期待値を確認する

  • 締切ちょうどを受付に含めるか、仕様を確認した。
  • 本番の時計とテストの時計は別名で、固定時計を使うテストだけに設定を取り込んだ。
  • 三つのテストで締切を変えず、現在時刻だけを変えた。
  • HTTPの200に加え、JSONの accepting と closesAt を確認した。

どこでBeanを作り、どこで受け取るかを整理したい場合は、『Spring徹底入門 第2版』のDI/AOPの解説が参考になります。コンストラクターで依存先を受け取る仕組みを学び、この記事のServiceとClockがどうつながるかを読み直せます。

書籍「Spring徹底入門 第2版」の表紙
商品画像:Amazon.co.jp
PR 入門後の参考書|Spring Framework 5向け

Spring徹底入門 第2版

株式会社NTTデータ (著), 株式会社NTTデータグループ (編集)

アプリを作った後に、DIやDB更新の仕組みを調べる。

DI、MVC、データアクセス、テスト、セキュリティまで幅広く確認できます。小さなWebアプリを一通り作り、Springの仕組みを詳しく学びたい人に向く参考書です。

  • Springで小さなWebアプリを作ったことがある
  • DIやトランザクションの仕組みを確認したい

Spring Framework 5向けです。Boot 3の実装に使うコード・設定は、採用している版の公式資料と照合してください。

当サイトはAmazonアソシエイト・プログラムの参加者です。価格・在庫・配送条件はAmazonでご確認ください。

関連記事JUnit 5入門|Mavenで最初のテストを実行し、失敗を直す MavenでJUnitを動かすところから確認したい場合に、実行件数と期待値の違いを読み取れます。 記事を読む 関連記事Spring Boot初心者におすすめの本3冊|現場で必要な力を身につける Spring Bootで機能を作り、依存関係とHTTPの動作を説明し、テストで確かめる力を身につける本を選べます。 記事を読む

まとめ

Spring Bootで締切を試すときは、判定のクラスへ Clock を渡し、テストだけで固定時計を選びます。同じ締切に対して、直前・ちょうど・直後のJSONを比べれば、締切と同じ瞬間を誤って受け付ける変更を検出できます。

-実装・エラー解決
-, ,