我正在使用spock进行应用程序测试并使用Grails 2.4.4。我已经完成了域,控制器和服务单元测试。但是在控制器部分,我坚持使用角色明智的访问方式。为了进行身份验证,我使用的是Spring Security Core插件。以下是我的示例代码。
@Secured(["IS_AUTHENTICATED_FULLY"])
def index(Integer max) {
}
@Secured(["ROLE_A","ROLE_B"])
def create() {
respond new DomainName(params)
}
@Transactional
@Secured(["ROLE_A","ROLE_B"])
def save(DomainName DomainNameInstance) {
}
如何测试只有具有ROLE_A和ROLE_B的用户才能创建和保存,而其他用户则不能创建?另外我还要检查用户是否IS_AUTHENTICATED_FULLY访问索引操作?
最佳答案
从您的问题看来,您似乎正在尝试测试Spring Security代码是否正常工作。我对单元测试控制器的看法是:“如果我不写,就不会对其进行测试。”控制器使用的服务被模拟,控制器使用的配置值被模拟。同样,Spring Security行为是模拟的(实际上)。这意味着要承担与您在应用程序中使用的插件有关的一定风险。您是否相信Spring Security能够正确处理角色和权限?我一般。
我对代码的行为更感兴趣,因此我通常只在单元测试中绕过弹簧检查。如果要验证应用程序的行为(如果用户已登录或未登录,或者具有或没有特定角色),则可以执行此操作。
def "test create method without required role"() {
setup:
// tell Spring to behave as if the user does not have the desired role(s)
SpringSecurityUtils.metaClass.static.ifAllGranted = { String role ->
return false
}
when:
controller.index()
then:
// without the required role, what does the controller return?
controller.response.status == ??
cleanup:
SpringSecurityUtils.metaClass = null
}
def "test create method with required role"() {
setup:
// tell Spring to behave as if the user has the required role(s)
SpringSecurityUtils.metaClass.static.ifAllGranted = { String role ->
return true
}
when:
controller.index()
then:
// with the required role(s), what does the controller return?
controller.response.status == 200
controller.response.mimeType.name == "application/json"
controller.response.getText() == "whatever"
cleanup:
SpringSecurityUtils.metaClass = null
}