Reputation: 685
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
Reputation: 7713
import grails.test.*
class UserControllerTests extends ControllerUnitTestCase {
void testIndex() {
controller.index()
assertEquals controller.list, controller.redirectArgs["action"]
}
}
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 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
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