How to mock SpringSecurityService in unit test

I am testing a Grails controller module that internally creates a user instance. The user class uses springSecurityServicethe Spring security plugin to encode the password before inserting it into the database.

Is there a way to mock springSecurityServicefrom my unit test to get rid of this error?

 Failure:  Create new individual member(MemberControllerSpec)
|  java.lang.NullPointerException: Cannot invoke method encodePassword() on null object

Please find my unit test below.

@TestMixin(HibernateTestMixin)
@TestFor(MemberController)
@Domain([User, IndividualPerson])
class MemberControllerSpec extends Specification {

void "Create new individual member"() {

    given:
    UserDetailsService userDetailsService = Mock(UserDetailsService)
    controller.userDetailsService = userDetailsService

    def command = new IndividualPersonCommand()
    command.username = 'scott@tiger.org'
    command.password = 'What ever'
    command.firstname = 'Scott'
    command.lastname = 'Tiger'
    command.dob = new Date()
    command.email = command.username
    command.phone = '89348'
    command.street = 'A Street'
    command.housenumber = '2'
    command.postcode = '8888'
    command.city = 'A City'

    when:
    request.method = 'POST'
    controller.updateIndividualInstance(command)

    then:
    view == 'createInstance'

    and:
    1 * userDetailsService.loadUserByUsername(command.username) >> null

    and:
    IndividualPerson.count() == 1

    and:
    User.count() == 1

    cleanup:
    IndividualPerson.findAll()*.delete()
    User.findAll()*.delete()
}
}
+4
source share
2 answers

You can use this code to encode a password in User:

def beforeInsert() {
    encodePassword()
}

def beforeUpdate() {
    if (isDirty('password')) {
        encodePassword()
    }
}

protected void encodePassword() {
    password = springSecurityService?.passwordEncoder ? springSecurityService.encodePassword(password) : password
}

When springSecurityServicenull, encodePasswordit is not called and the NPE does not rise

0
source

- Groovy MetaClass

import grails.test.mixin.Mock
import grails.plugin.springsecurity.SpringSecurityService

...
@Mock(SpringSecurityService)
class MemberControllerSpec extends Specification {

    def setupSpec() {
        SpringSecurityService.metaClass.encodePassword = { password -> password }
    }

    def cleanupSpec() {
        SpringSecurityService.metaClass = null
    }
....

SpringSecurityService.encodePassword() .

Mocks .

+3

Source: https://habr.com/ru/post/1605718/


All Articles