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

问题描述 投票:0回答:1

我可以在如何模拟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", "[email protected]", "Secret1234" )
        //^(does some validation, then User.save())
        User foundUser = User.findByEmail("[email protected]")
        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
    }

没有存根或嘲笑此依赖项,我得到了错误

Cannot invoke method isPasswordValid() on null object

我试图存根密码编码器并使它返回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模拟这种依赖关系?

unit-testing grails spring-security mocking spock
1个回答
0
投票

Stub和Mock接受一个类-您为其提供了一个实例,该实例为null-因此是例外。

您应该能够像这样嘲笑它:

def mockPasswordEncoder = Mock(PasswordEncoder) 
// note this is the class 
// org.springframework.security.crypto.password.PasswordEncoder
© www.soinside.com 2019 - 2024. All rights reserved.