0

I want to mock function like Files.copy(), LocalDate.now() from Java e.g. In one of my function I have

public int functionForTest(){
    var now = LocalDate.now()
    if(now.getMonth() == 2)
       return 55;
    if(now.getMonth() == 4)
       return 22;
}

and based on current month I have to return some value but when I want to test this function I have to mock LocalDate.now(). Does someone know how to mock this function?

Mateusz Sobczak
  • 1,551
  • 8
  • 33
  • 67
  • Do you have control over the source code? It would be easier to just refactor it for better testability (see e.g. [this answer](https://stackoverflow.com/questions/32792000/how-can-i-mock-java-time-localdate-now)). – slauth Oct 06 '21 at 07:15
  • So it will be better to create provider class wich return current date? what if I can't change code? – Mateusz Sobczak Oct 06 '21 at 09:04
  • For this specific case you don't have to write a class since there is `Clock` already. See my linked answer. If you can't change the code you're out of luck I guess. – slauth Oct 06 '21 at 10:00

1 Answers1

0

In Groovy you can mock almost everything using meta-programming:

import java.time.*

LocalDate.metaClass.static.now = {->
  delegate.of 2010, 5, 5
}

assert '2010-05-05' == LocalDate.now().toString()
injecteer
  • 20,038
  • 4
  • 45
  • 89
  • In my case it doesn't work. It mocks now() method but only in test method not in method which I want to test – Mateusz Sobczak Oct 06 '21 at 09:02
  • it replaces the static method in the scope of execution of your testcase for the groovy classes. If you call `LocalDate.now()` from java, then you have greater problems – injecteer Oct 06 '21 at 09:12
  • I'm using LocalDate.now() in java class – Mateusz Sobczak Oct 06 '21 at 09:14
  • you have 2 options: 1) "inject" the LocalDate somehow by using a `Supplier` and rearrange the rest of code 2) turn your java-class into groovy and do nothing more – injecteer Oct 06 '21 at 09:29
  • Or use an add-on tool like Mockito or Sarek if you wish to mock static Java methods. But refactoring for no longer needing to mock static methods is preferable. – kriegaex Oct 17 '21 at 08:24