gpt4 book ai didi

使用 Spock 进行测试时,Grails 无法将服务注入(inject)域

转载 作者:行者123 更新时间:2023-12-02 14:49:22 25 4
gpt4 key购买 nike

使用 Spock 进行 grails 单元测试时,无法自动将服务实例注入(inject)域。

下面是我的代码。

服务:

class HiService {

public HiService(){
println "Init HiService," + this.toString()
}

def sayHi(String name){
println "Hi, ${name}"
}
}


领域:

class User {

public User(){
if (hiService == null){
println "hiService is null when new User(${name})"
}
}

String name

def hiService

def sayHi(){
println "Before use hiService " + hiService?.toString()
hiService.sayHi(name)
println "End use hiService" + hiService?.toString()
}
}


测试用例:

@TestFor(HiService)
@Mock([User])
class HiServiceTest extends Specification {

def "test sayHi"() {

given:
def item = new User( name: "kitty").save(validate: false)

when: "Use service method"
item.sayHi()

then : "expect something happen"
assertEquals(1, 1)
}
}


以下是控制台日志:

--Output from test sayHi--
Init HiService,test.HiService@530f5e8e
hiService is null when new User(null)
Before use hiService null
| Failure: test sayHi(test.HiServiceTest)
| java.lang.NullPointerException: Cannot invoke method sayHi() on null object
at test.User.sayHi(User.groovy:17)
at test.HiServiceTest.test sayHi(HiServiceTest.groovy:20)


服务已初始化,但无法注入(inject)域。但是当直接运行应用程序时,服务会自动注入(inject)到域中

最佳答案

如果您不想 Autowiring ,则需要进行集成测试。如果使用 Grails 3,则使用 @Integration 进行注释,如果使用 grails 2,则扩展 IntegrationSpec。

见:http://docs.grails.org/latest/guide/testing.html#integrationTesting

关于使用 Spock 进行测试时,Grails 无法将服务注入(inject)域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41520086/

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