Spring Boot测试如何模拟系统时钟?现有代码为何不生效?
问题分析与解决
测试代码无效的核心原因
你创建的固定时钟Clock.fixed(...)完全没被原方法用到:
- 测试里的
Instant.now(Clock.fixed(...))只是生成了一个固定时间的Instant对象,但原方法中的new Date()依然调用系统默认时间(底层依赖System.currentTimeMillis()),根本不会关联你创建的这个时钟。
原方法还有个格式错误
你的SimpleDateFormat格式字符串写的是yyyy-MM-dd'T'HH:mm:ss.sss'Z',其中毫秒部分的sss是小写的s,这是错误的:小写s代表秒,毫秒应该用大写的SSS,否则格式化出来的毫秒部分会是秒的重复值,导致时间格式不符合预期。
方案1:重构原方法(推荐,符合现代Java实践)
把原方法改成依赖可注入的Clock,这样测试时可以传入固定时钟,生产环境用系统默认时钟:
修改后的原方法
public class LogUtils { // 供测试调用,传入指定时钟 public static String formatTimestamp(Clock clock) { TimeZone timeZone = TimeZone.getTimeZone("UTC"); // 修正格式字符串的毫秒部分为SSS DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); dateFormat.setTimeZone(timeZone); return dateFormat.format(Date.from(clock.instant())); } // 供生产代码调用,使用系统UTC时钟 public static String formatTimestamp() { return formatTimestamp(Clock.systemUTC()); } }
对应的测试代码
import org.junit.jupiter.api.Test; import java.time.Clock; import java.time.Instant; import java.time.ZoneOffset; import static org.junit.jupiter.api.Assertions.assertEquals; class LogUtilsTest { @Test void test_Format_Timestamp_Success() { String expectedNow = "2023-09-26T12:00:00.000Z"; // 创建固定时钟 Clock fixedClock = Clock.fixed(Instant.parse(expectedNow), ZoneOffset.UTC); String currentTimeStamp = LogUtils.formatTimestamp(fixedClock); assertEquals(expectedNow, currentTimeStamp); } }
方案2:不修改原方法,用PowerMock拦截系统时间
如果无法修改原方法,可以用PowerMock来mockSystem.currentTimeMillis()方法,强制返回固定时间戳:
测试代码(需引入PowerMock依赖)
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit5.PowerMockExtension; import java.time.Instant; import java.time.ZoneOffset; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.powermock.api.mockito.PowerMockito.mockStatic; import static org.powermock.api.mockito.PowerMockito.when; @ExtendWith(PowerMockExtension.class) @PrepareForTest(LogUtils.class) class LogUtilsTest { @Test void test_Format_Timestamp_Success() { String expectedNow = "2023-09-26T12:00:00.000Z"; Instant fixedInstant = Instant.parse(expectedNow); long fixedMillis = fixedInstant.toEpochMilli(); // mock System类的静态方法 mockStatic(System.class); when(System.currentTimeMillis()).thenReturn(fixedMillis); String currentTimeStamp = LogUtils.formatTimestamp(); assertEquals(expectedNow, currentTimeStamp); } }
内容的提问来源于stack exchange,提问作者Ahmed Tharwat
相关产品推荐
相关产品推荐

