Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails Spring Security Testing

I use the Grails Spring Security Plugin for my project and now want to unit test my code. I have the following code in my controller:

def index() {
    redirect action: 'show', params: [id: springSecurityService.currentUser.id]
}

My Test Class has the following code:

void testIndex() {      
    controller.index()
    assert "/user/list" == response.redirectedUrl
}

This test fails:

| Running 8 unit tests... 1 of 8
| Failure:  testIndex(xxx.UserControllerTests)
|  java.lang.NullPointerException: Cannot get property 'currentUser' on null object
    at xxx.UserController.index(UserController.groovy:12)
    at xxx.UserControllerTests.testIndex(UserControllerTests.groovy:19)

How can I authenticate a spring security user in a test case? How would you write the unit test?

like image 955
dildik Avatar asked Oct 09 '12 19:10

dildik


2 Answers

You have to use functional tests for security. Unit tests use mocking but don't have plugins available, or a real request. Spring Security is implemented with a filter chain, so you need a real running server. If you use mocks, you're just testing the mocking.

like image 168
Burt Beckwith Avatar answered Oct 07 '22 15:10

Burt Beckwith


For something this simple I wouldn't bother with complicated mocks, a straightforward

controller.springSecurityService = [currentUser:[id:1]]

would be sufficient.

like image 23
Ian Roberts Avatar answered Oct 07 '22 14:10

Ian Roberts