gpt4 book ai didi

java - 时间相关的单元测试在并行运行时中断,有什么解决方法吗?

转载 作者:行者123 更新时间:2023-11-30 09:18:12 24 4
gpt4 key购买 nike

我有时间相关的单元测试,我必须在其中模拟“现在”。我使用 JodaTime,当我需要模拟 now 的值以进行时间相关测试时,我使用 DateTimeUtils.setCurrentMillisFixed(...),如相关已接受答案中的建议 Time dependent unit tests .

但是,当单元测试并行运行时,这现在会导致问题。正确的解决方案是让所有类从 Clock 依赖项获取当前时间,该依赖项可以在测试中模拟(如 Time dependent unit tests 中最受支持的答案所建议的那样)。但是,我目前没有足够的开发资源来进行重构工作。

我的问题是有没有办法通过某种方式指定哪些测试可以并行运行而哪些不能并行运行来解决这个问题?有没有办法通过使用 DateTimeUtils.setCurrentMillisProvider() 来解决这个问题?

测试框架是 JUnit4,测试从 maven 运行。

最佳答案

实现并设置一个 CurrentMillisProvider将“现在”存储在 ThreadLocal<Long> 中,正如这些 Parallelism Tips 中所建议的那样:

P.S. Joda Time has DateTimeUtils which lets you change the current time used by the library. It's a global variable, but if you call DateTimeUtils.setCurrentMillisProvider with a ThreadLocal backed implementation, it'll be reasonably isolated when testing legacy code that uses Joda Time.

关于java - 时间相关的单元测试在并行运行时中断,有什么解决方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18591236/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com