【发布时间】:2020-12-16 10:05:02
【问题描述】:
我试图覆盖 java.time.Year 类的公共静态方法 now() 因为我希望它返回一个不同的值,而不仅仅是当前年份。在我的生产代码中,我有一个正在测试的方法,它使用 Year.now() 方法:
被测Java类
public class SomeClass {
public LocalDate methodUnderTest() {
return Year.now()
.atMonth(JANUARY)
.atDay(1);
}
}
在 Spock groovy 测试中,我尝试以这种方式覆盖 java.time.Year.now() 方法: 我打算在我的生产代码中使用静态方法 now() 的覆盖行为,方法是 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)
}
}
但是,该测试仅适用于 2020 年(当年),其他两个值 2019 和 2021 不起作用,因为似乎预期的覆盖行为显然没有在生产代码中使用。 为什么在运行时 methodUnderTest() 的生产代码中没有使用预期的覆盖行为?
【问题讨论】:
标签: testing groovy overriding runtime spock