在Grails中,如何在自动化测试中测试@Secured注释?

时间:2013-05-31 03:17:35

标签: unit-testing grails spring-security integration-testing

我有一个控制器方法,我是这样注释的:

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

我正在尝试编写一个单元测试来验证只有管理员用户才能访问该网址:

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

    when:
    controller.save()

    then:
    view ==~ 'accessdenied'
}

但是,返回的视图是save视图,而不是访问被拒绝视图。看起来它完全绕过了@Secured注释。有没有办法从单元测试或集成测试中测试@Secured注释?

2 个答案:

答案 0 :(得分:2)

试试这个:

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

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

答案 1 :(得分:0)

如果您未在createNonAdminUser()中进行操作,则需要在调用控制器保存之前登录用户。

SpringSecurityUtils.reauthenticate username, password

可能与this问题有关。

相关问题