In Grails, how can I test @Secured annotations in automated tests?

I have a controller method that I write like this:

@Secured(['ROLE_ADMIN']) def save() { ... // code ommitted } 

I am trying to write unit test to make sure that only the admin url can hit the url:

 def "Only the admin user should be able to invoke save"() { given: def user = createNonAdminUser() // let pretend this method exists controller.springSecurityService = Mock(SpringSecurityService) controller.springSecurityService.currentUser >> user when: controller.save() then: view ==~ 'accessdenied' } 

However, the returned view is a save view, not a type of access ban. It looks like it generally bypasses the @Secured annotation. Is there a way to test @Secured annotations from unit test or integration?

+4
source share
2 answers

Try the following:

 SpringSecurityUtils.doWithAuth('superuser') { controller.save() } 

http://greybeardedgeek.net/2011/05/13/testing-grails-controllers-with-spock/

+2
source

You will need to log in before calling the controller controller if you are not already running it in createNonAdminUser() .

SpringSecurityUtils.reauthenticate username, password

Perhaps related to this issue.

0
source

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


All Articles