1

We use

LocalDate.now() and 
Instant.now() 

in our Application. Working on Unit testing and would like to test few things with Future Date and Past date. We do change the System clock and testing this. Is it possible to do these kind of testing without Changing the system clock.

We have the following option.

LocalDate.now(Clock clock)

But, the problem is, we are using LocalDate.now() in so many places and hence changing the code is not an option.

Udaya Vani
  • 513
  • 1
  • 6
  • 20
  • I'm not sure if I've understood your query fully, but is this what you are looking for? ` Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DAY_OF_YEAR, 15); Date futureDate = calendar.getTime();` – N00b Pr0grammer Apr 16 '16 at 05:06
  • Why don't you try LocalDate tomorrow = LocalDate.now().plusDays(1); and LocalDate yesterday = LocalDate.now().minusDays(1); to play with future date and past date – Unknown Apr 16 '16 at 05:08
  • 3
    See [my answer](http://stackoverflow.com/questions/36178388/how-to-mock-static-method-that-returns-final-class/36178992#36178992) to [a question about mocking and testing](http://stackoverflow.com/questions/36178388/how-to-mock-static-method-that-returns-final-class). It does not deal with date and time, but the mechanism is the same. Unfortunately, you have to touch your code (at all those places). But in terms of quality, I think you want to improve your code, don't you? – Seelenvirtuose Apr 16 '16 at 05:09
  • I want Localdate.now() to return future or past date without changing the system clock. – Udaya Vani Apr 16 '16 at 05:10
  • 1
    Really, you don't want to _change_ `LocalDate`'s behavior. You want to unit-test your code that has a dependency to some date and/or time providing concepts. In fact, [you are asking for _X_ but you want to achieve _Y_](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – Seelenvirtuose Apr 16 '16 at 05:12
  • @Seelenvirtuose I suggest you write up your comments as an Answer. You are correct, the OP needs to alter their existing code to make it testable despite their reluctance. – Basil Bourque Nov 01 '18 at 20:40

1 Answers1

0

This isn't an unusual desire, and while the best solution is generally to rewrite the code to be a little more testable, people have used mocking to do this kind of thing. That's the kind of solution that needs to be surrounded by disclaimers on all sides, though. Friends don't let friends do this.

arnt
  • 8,949
  • 5
  • 24
  • 32