gpt4 book ai didi

grails - 无法在 Grails 3 中填充 java.util.getTimeZone 以进行 Taglib 中的 spock 测试

转载 作者:行者123 更新时间:2023-12-02 11:35:56 30 4
gpt4 key购买 nike

我被困在 Grails 3 spock 标签库测试中的某个地方。我想测试 taglib 的闭包,如下所示:

ATagLib.groovy:

Closure a = {attrs ->
java.util.TimeZone utc = java.util.TimeZone.getTimeZone(FraudnetConstants.TIMEZONE_UTC)
if (attrs.somevar) {
out << "${g.message(code: 'some.code')} ${g.formatDate([date: attrs.date, format: "h:mma", timeZone: utc])}"
} else if (attrs.freq == SomeConstants.VAL || attrs.freq == SomeConstants.VAL) {
out << g.formatDate([date: attrs.date, format: "E '@' h:mma", timeZone: utc])
} else {
out << "${g.message(code: 'some.other.code')} ${g.formatDate([date: attrs.date, format: "h:mma", timeZone: utc])}"
}
}

我的ATagLibSpec.groovy看起来像:

@TestFor(ATagLib)
class ATagLibSpec {
def setup() {
java.util.TimeZone.metaClass.'static'.getTimeZone = {a -> return null }
}

void 'testmethod'() {
expect:
taglib.a()
}
}

我在运行测试用例时遇到的异常是:java.lang.NullPointerException:无法在 groovy.lang.Closure.call( org.grails.plugins.web.taglib.FormatTagLib$_closure2.doCall(FormatTagLib.groovy:170) 处的 null 对象上调用方法 getTimeZone()关闭.java:414) 在 org.grails.taglib.TagOutput.captureTagOutput(TagOutput.java:64) 在 org.grails.taglib.TagLibraryMetaUtils.methodMissingForTagLib(TagLibraryMetaUtils.groovy:138) 在 org.grails.taglib.NamespacedTagDispatcher.methodMissing(NamespacedTagDispatcher.groovy:59)

有人可以指出,上述预填充 getTimeZone 的方法有什么问题吗?

最佳答案

最好不要使用元编程,而是将 TimezoneFactoryService 注入(inject)到标记库中。根据我的经验,必须在测试中进行元编程是代码味道的表现:您的代码使用静态方法来实例化对象,而不是依赖注入(inject)。

您的代码可能如下所示:

Closure a = {attrs->
java.util.TimeZone utc = timezoneFactoryService.getTimeZone(FraudnetConstants.TIMEZONE_UTC)
}

这将允许您通过使用常规的 Spock Mock 以更方便的方式模拟规范中的工厂服务。

@TestFor(ATagLib)
class ATagLibSpec {
def setup() {
taglib.timezoneFactoryService=Stub(TimezoneFactoryService) {
getTimeZone(_) >> null
}
}
void 'testmethod'() {
expect:
taglib.a()
}
}

关于grails - 无法在 Grails 3 中填充 java.util.getTimeZone 以进行 Taglib 中的 spock 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41740856/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com