mercredi 16 décembre 2020

Groovy metaClass override java.time.Year static method now() but productive code is not using the overriden behaviour of now() at runtime

I attempted to override the java.time.Year class's public static method now() because I want it to return a different value, not just the current year. In my productive code, I have a method which I am testing and it is using the Year.now() method as:

Java class under test

public class SomeClass {

  public LocalDate methodUnderTest() {
    return Year.now()
        .atMonth(JANUARY)
        .atDay(1);
  }

}

In the Spock groovy test, I attempted to override the java.time.Year.now() method this way: I intend that the overriden behaviour of the static method now() is used in my productive code, in the method methodUnderTest()

class SomeClassSpec extends Specification {

  @Subject
  SomeClass classUnderTest = new SomeClass()

  def "test method with overriden behaviour"() {

    setup:
    Year.metaClass.'static'.now = { -> Year.of(year) }

    expect:
    classUnderTest .methodUnderTest() == expectedDate

    where:
    year           || expectedDate
    2019           || LocalDate.of(2019, JANUARY, 1)
    2020           || LocalDate.of(2020, JANUARY, 1)
    2021           || LocalDate.of(2021, JANUARY, 1)
  }
}

However, the test only works for the year 2020 (the current year), the other 2 values 2019 and 2021 are not working because it seems that the intended overriden behaviour is obviously not used in the productive code. Why is the intended overriden behaviour not used in the productive code of methodUnderTest() at runtime?

Aucun commentaire:

Enregistrer un commentaire