gpt4 book ai didi

unit-testing - 如何在 Grails 单元测试中使用 Spock 模拟 passwordEncoder

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

我可以使用一些建议来模拟 Grails 单元测试中使用的自动连接依赖项。我已经省略了大部分不必要的代码,只给出了测试类和被测文件类中的相关方法

class UserService {

def springSecurityService // spring bean
def passwordEncoder // auto wired as per
//https://stackoverflow.com/questions/33303585/spring-//security-encode-password-with- bcrypt-algorithm

.....

def passwordPreviouslyUsed(String newPassword, def userId){
def passwordExists = false
def usersPasswords = findPasswordsForUser(userId)
usersPasswords.each{ password ->
if (passwordEncoder.isPasswordValid(oldPassword, newPassword, null)) {
passwordExists = true
}
}
return passwordExists
}

.....
def findPasswordsForUser(def userId){
User foundUser = User.findById(userId)
def passwordsForUser = UserPasswords.createCriteria().list {
eq('user', foundUser)
projections{
property('password')
}
}
passwordsForUser
}

我的测试
class UserServiceSpec extends Specification implements DataTest, ServiceUnitTest<UserService> {

def passwordEncoder
def setupSpec() {
mockDomains User, UserPasswords
}

def setup() {
def stubPasswordEncoder = Stub(passwordEncoder) {
isPasswordValid(_, _, _) >> true
}
service.passwordEncoder = stubPasswordEncoder
}


void "test for user passwordPreviouslyUsed"() {
given: "a user already exists"
setup()
service.createNewUser("testName", "testy@test.com", "Secret1234" )
//^(does some validation, then User.save())
User foundUser = User.findByEmail("testy@test.com")
foundUser.fullName == "testName"
long testUserId = foundUser.id

and: "we update the password for that user, and it to the userPasswords"
UserPasswords newUserPassword = new UserPasswords(
user: foundUser,
password: "newPassword1"
)
newUserPassword.save()

//use passwordPreviouslyUsed method to check a string with the same value as the
//previously
//updated password to check if it has already been used
when: "we check if the password has been used before"

def response = service.passwordPreviouslyUsed("newPassword1", fundsyId)

then:
response == true
}

没有 stub 或模拟这种依赖关系,我得到了错误
Cannot invoke method isPasswordValid() on null object

我试图 stub 密码编码器并让它返回 true
def stubPasswordEncoder =  Stub(passwordEncoder) {
isPasswordValid(_, _, _) >> true
}
service.passwordEncoder = stubPasswordEncoder

但这给出了一条错误消息:
Stub in 'spock.mock.MockingApi' cannot be applied to         '(java.lang.Object, groovy.lang.Closure)'

有没有办法用 Spock 模拟这种依赖关系?

最佳答案

Stub 和 Mock 接受一个类——你给它一个为空的实例——因此是异常。

您应该可以这样模拟它:

def mockPasswordEncoder = Mock(PasswordEncoder) 
// note this is the class
// org.springframework.security.crypto.password.PasswordEncoder

关于unit-testing - 如何在 Grails 单元测试中使用 Spock 模拟 passwordEncoder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61128624/

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