我有一个控制器方法,我正在这样注释:
@Secured(['ROLE_ADMIN'])
def save() {
... // code ommitted
}
我正在尝试编写单元测试以验证只有管理员用户可以访问该URL:
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'
}
但是,返回的视图是保存视图,而不是拒绝访问视图.看起来它完全绕过了@Secured注释.有没有办法从单元测试或集成测试中测试@Secured注释?
最佳答案 试试这个:
SpringSecurityUtils.doWithAuth('superuser') {
controller.save()
}
http://greybeardedgeek.net/2011/05/13/testing-grails-controllers-with-spock/