【发布时间】:2012-05-08 23:31:58
【问题描述】:
我正在尝试使用在数据库表中查找当前“处理周期”的方法为服务编写集成测试。但是,并不总是有一个有效的处理周期,因此该方法可能会返回 null(有几周没有进行处理)。我想为这个方法写一个 JUnit 测试,但由于它不会总是返回一个值,我会根据我运行测试的时间得到不同的结果。
期间对象和服务看起来像:
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 有效。
【问题讨论】:
-
一个示例说明为什么编写返回 null 的代码被视为禁忌。 ;-)
-
使用示例测试数据运行测试总是更好,在您的设置中的测试运行之前创建一些测试数据,运行测试,最后删除这些记录。
标签: java testing junit mocking integration-testing