daigoor
daigoor

Reputation: 685

How can I test the session variables in Grails?

I have two issues with testing a Grails controller.

I have a controller contains some methods like this one:

def save() {
    def x =session.SPRING_SECURITY_CONTEXT.authentication.principal.id
    def user = User.get(x)
}

and to test this I wrote the test method like this:

def testSave () {
    myCont.save()
}

And when I run this, I see a WARN from the database while getting the user which is:

[main] WARN core.DatastoreUtils - Cannot unbind session, there's no SessionHolder registered

So, my questions are:

Upvotes: 4

Views: 4147

Answers (3)

Daniel Wondyifraw
Daniel Wondyifraw

Reputation: 7713

Have u tried this one ?

import grails.test.*
class UserControllerTests extends ControllerUnitTestCase {
    void testIndex() {
      controller.index()
      assertEquals controller.list, controller.redirectArgs["action"]
    }
}

assuming this controller to test

def index = {
  if(session?.user?.role == "admin"){
    redirect(action:list,params:params)
  }else{
    flash.message = "Sorry, you are not authorized to view this list."
    redirect(controller:"home", action:index)
  }

Testing

Testing for session and flash values

void testIndex() {
  def jdoe = new User(name:"John Doe", role:"user")
  def suziq = new User(name:"Suzi Q", role:"admin")

  controller.session.user = jdoe
  controller.index()
  assertEquals "home", controller.redirectArgs["controller"]
  assertTrue controller.flash.message.startsWith("Sorry")

  controller.session.user = suziq
  controller.index()
  assertEquals controller.list, controller.redirectArgs["action"]
} 

for detailed reference [1]: http://www.ibm.com/developerworks/java/library/j-grails10209/

Upvotes: 0

user854577
user854577

Reputation:

If you're trying to unit test it and would just like to stub it out (and aren't using anything with more sophisticated mocking/stubbing) you could do it quick and easy with a map. Put @TestFor(YourControllerClass) right above your test class declaration. Then you can do something like:

controller.session.SPRING_SECURITY_CONTEXT = [authentication:[principal:[id: 'blah']]]

Upvotes: 2

moskiteau
moskiteau

Reputation: 1102

You should do an Integration test and set the session yourself as shown here.

Upvotes: 0

Related Questions