我有一个更简单的 Controller 方法,可以执行以下操作:
def updateName(){
def idUser = params.id
User changeUser = User.get(idUser)
changeUser.name = "newname"
changeUser.save(flush: true)
}
以及以下Spock测试:def "updateName should edit user and save it"(){
given: "the id of the user"
User currentUser = new User([name: "hector" , age: 12]).save(flush: true)
params.id = User.last().id
when: "the updateName method is called"
controller.updateName()
then: "name should have change it and save has to be called just one time"
assert currentUser.name == "newname" // Success
1 * _.save() // Too few invocations, 0.
}
我已经在SO中看到了与此主题相关的所有相关问题,有人建议使用Mocks和Spy,但我真的不明白为什么要使用它们,无论如何我都没有让它们为我工作。创建一个用户模拟并将我的基数断言更改为:1 * userMock.save()
但这对我没有用...我可以帮上忙吗?
最佳答案
为了使其正常工作,我创建了一个GroovyMock,它使我可以访问静态功能(例如保存)。
def "updateName should edit user and save it"(){
given: "the id of the user"
params.id = 1
User mockUser = GroovyMock(User, global: true)
when: "the updateName method is called"
controller.updateName()
then: "set Name and save has to be called just one time"
1 * User.get(1) >> mockUser
1 * mockUser.setName("newname")
1 * mockUser.save()
} //All test passed!
不知道这是否是最好的方法,但是对我有用!如果有人提供了更好的解决方案,或者抛出了一些很好的信息,我将保留问题。
关于unit-testing - 用Spock检查基数时调用太少0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62694797/