I am writing a functional test using cucumber for my Spring boot application. The logic which I want to test uses current time, based on that the result vary. Is there a way to mock the current time in functional tests
Asked
Active
Viewed 104 times
-1
-
Yes, there are ways of mocking current time. You should probably share what are you using for retrieving current time. – Ervin Szilagyi Aug 12 '18 at 11:32
1 Answers
0
That's possible using PowerMock http://powermock.github.io/
@RunWith(PowerMockRunner.class)
// ... other annotations
public class SomeTest {
private final Date fixedDate = new Date(10000);
@Before
public void setUp() throws Exception {
PowerMockito.whenNew(Date.class).withNoArguments().thenReturn(fixedDate);
}
...
}
Another approach is to use some service that provides current time and mock this service in the test. Rough example
@Service
public class DateProvider {
public Date current() { return new Date(); }
}
@Service
public class CurrentDateConsumer {
@Autowired DateProvider dateProvider;
public void doSomeBusiness() {
Date current = dateProvider.current();
// ... use current date
}
}
@RunWith(Cucumber.class)
public class CurrentDateConsumerTest {
private final Date fixedDate = new Date(10000);
@Mock DateProvider dateProvider;
@Before
public void setUp() throws Exception {
when(dateProvider.current()).thenReturn(fixedDate);
}
}

Nikolai Shevchenko
- 7,083
- 8
- 33
- 42
-
-
@Priya, seems to. I've updated my answer for more universal solution – Nikolai Shevchenko Aug 12 '18 at 11:45