5

There is a pretty cool concept of a Ticker in Guava. Unfortunately, it seems like it was designed around generating nano-second focused Stopwatches for measuring execution durations.

I'd like to find something to use like this because, it makes testing classes sensitive to time changes easier. I have run into an issue historically when I used System.currentTimeMillis() because its hard to simulate the passage of time in a test. I was thinking of using a similar interface to what Guava has but measuring times in millis instead since that matches more of the available libraries.

I wanted to ask if anyone has seen something similar or has other suggestions before I go write it myself.

4

3 回答 3

5

正如您所指出的,Ticker是用于测量经过的时间(System.nanoTime()用途),而不是挂钟时间(System.currentTimeMillis()用途),您不应该使用它来获取它。

我建议创建一个抽象Clock类,Ticker但要以毫秒为单位获取挂钟时间。

于 2012-09-22T04:32:47.947 回答
4

这就是我在项目中使用的:

public interface Clock {
    LocalDate today();
    LocalTime time();
    LocalDateTime now();
    long timestamp();
}

正如您所说,它使单元测试变得更加简单(甚至可能)。我有一个实现,它总是返回真正的时间和一个FakeClock我可以控制的。它的实现非常简单,你可以轻松地自己动手——我认为 Guava 中没有类似的东西。

这种方法也在越来越多的面向对象软件,由测试指导中描述和推荐。

于 2012-09-22T07:15:53.487 回答
0

编辑:经过进一步思考,我喜欢 Christoph 和 Colin 的建议。为挂钟提供类似功能的想法会很好。

正如所指出的,这里最好的策略可能只是实现一个从 Ticker 读取毫秒时间的方法。

于 2012-09-22T03:26:38.213 回答