1

我正在尝试使用在数据库表中查找当前“处理周期”的方法为服务编写集成测试。但是,并不总是有一个有效的处理周期,因此该方法可能会返回 null(有几周没有进行处理)。我想为这个方法编写一个 JUnit 测试,但由于它不会总是返回一个值,我会根据我运行测试的时间得到不同的结果。

period 对象和服务如下所示:

public interface ProcessingPeriod {
    int getSeqno();
    Date getStart();
    Date getEnd();
}

public class PeriodService {
    /* Look up the current period; if not currently in a period, return null */
    public ProcessingPeriod getCurrentPeriod() { /* execute a sql query */ }

    /* Look up the current period; if not currently in a period, get the next upcoming period */
    public ProcessingPeriod getCurrentOrNextPeriod() { /* execute a sql query */ }

    /* Look up the current period; if not currently in a period, get the most recent period */
    public ProcessingPeriod getCurrentOrPreviousPeriod() { /* execute a sql query */ }
}

的实例PeriodService由 Spring 应用程序上下文管理,我的 JUnit 测试使用SpringJUnit4ClassRunner来构造测试上下文并将服务对象提供给测试。我的 JUnit 测试目前看起来像:

@Test
public void testGetCurrentPeriod() {
    ProcessingPeriod period = service.getCurrentPeriod();
    if (period != null) {
        Date now = new Date();
        assertThat(period.getStart(), lessThanOrEqualTo(now));
        assertThat(period.getEnd(), greaterThanOrEqualTo(now));
    }
}

但是,如果在处理期间不运行测试,这似乎没有多大帮助。我怎样才能有意义地测试该getCurrentPeriod方法实际上从数据库中获取了正确的时间段?我应该嘲笑数据库吗?我还想对数据库实际执行查询,以帮助确保 SQL 有效。

4

1 回答 1

1

instead of using in my code new Date(), getCurrentTimeMillis(), etc. i always use a time provider that contains all time related methods i need.

interface TimeProvider {
  Date getDate();
  int getCurrentQuarter();
  ...
}

production implementation is obvious. for tests, however, you can put any provider you need so you can set any time you like in tests. it works good with spring. but it works only when you test code that doesn't use it's own internal clock (sleep, lock, quartz, etc).

looks like it fits your example but you will have to refactor your production code

于 2012-05-10T12:03:21.547 回答