-1

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

Priya
  • 1,096
  • 4
  • 15
  • 32

1 Answers1

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