Here's a working way to override the current system time to a specific date for testing JUnit in a Java 8 web application using EasyMock
Joda Time is sure, good (thanks Steven, Brian, you made our world a better place), but I was not allowed to use it.
After some experimentation, I eventually came up with a way to mock time to a specific date in the Java 8 java.time API using EasyMock
- without Joda Time API
- and without PowerMock.
Here's what you need to do:
What you need to do in the test class
Step 1
Add the new java.time.Clock attribute to the MyService class being tested and make sure that the new attribute is correctly initialized by default with the help of the instantiation block or constructor:
import java.time.Clock; import java.time.LocalDateTime; public class MyService {
Step 2
Introduce the new clock attribute into the method that calls the current date-time. For example, in my case, I had to check if the date stored in dataase happened before LocalDateTime.now() , which I moved using LocalDateTime.now(clock) , for example:
import java.time.Clock; import java.time.LocalDateTime; public class MyService {
What you need to do in the test class
Step 3
In the test class, create a mock clock object and enter it into the tested instance of the class just before you call the proven doExecute() method, then reset it will appear again like this:
import java.time.Clock; import java.time.LocalDateTime; import java.time.OffsetDateTime; import org.junit.Test; public class MyServiceTest {
Check it in debug mode, and you will see that the February 3, 2017 date was correctly entered into the MyService instance and used in the comparison instruction, and then it was correctly reset to the current date using initDefaultClock() .
KiriSakow Aug 23 '17 at 7:21 2017-08-23 07:21
source share