How to get the currentUser provided by spring security in Grails 2 unit testing

Hi guys i am on trouble about getting the current user provided by spring.

Here's my unit test code

   void "Test if adding project will sucess"() {

        def createProjectMock = mockFor(UserService)

        createProjectMock.demand.createNewProject { Map projectMap ->
            return true

        controller.userService = createProjectMock.createMock()

    when: "saveProject is execute"


    then: "page will to the list to view the saved project"
        response.redirectedUrl == '/user/index2'

Here's my controller

def saveProject(ProjectActionCommand projectCmd) {

  def currentUser = springSecurityService.currentUser
  if (projectCmd.hasErrors()) {

    render view: 'createProject', model: [projectInstance: projectCmd, user:currentUser]
  } else {

    def getProjectMap = [:]

    getProjectMap = [
      projectName: params.projectName,
      user: currentUser

    def saveProject = userService.createNewProject(getProjectMap)

    if (saveProject) {   

      redirect view: 'index2'         
    } else {
      render 'Error upon saving'

And here's my service

  Project createNewProject(Map projectMap){
    def createProject = new Project()

    createProject.with {
      projectName = projectMap.projectName
      user = projectMap.user
    }, flush: true)

And i always getting this error:

Cannot get property 'currentUser' on null object.

Hope you can help me. Thanks

1 answer

  • answered 2018-07-19 23:02 Michal_Szulc

    Cannot get property 'currentUser' on null object.

    means that you haven't mocked springSecurityService. Let's do it in setup section (I assume it may be useful also in other methods in this class):

    def springSecurityService
    def setup() {
        springSecurityService = Mock(SpringSecurityService)
        controller.springSecurityService = springSecurityService

    At this point your code is going to work. However remember that you can always mock also the actual logged user and test it at any point:

        User user = Mock(User)
        springSecurityService.currentUser >> user