I'm trying to write an integration test for a service with a method that looks up the current "processing period" in a database table. However, there is not always an active processing period, so the method may return null (there are weeks where no processing occurs). I would like to write a JUnit test for this method, but since it won't always return a value, I'll get different results depending on when I run the test.
The period object and service looks like:
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 */ }
}
An instance of PeriodService
is managed by a Spring application context, and my JUnit test uses the SpringJUnit4ClassRunner
to construct a test context and provide the service object to the test. My JUnit test currently looks like:
@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));
}
}
But that doesn't seem like it's going to help much if the test isn't run during a processing period. How can I meaningfully test that the getCurrentPeriod
method actually gets the right period from the database? Should I be mocking the database? I had also wanted to actually execute the query against the database to help ensure the SQL is valid.