Grails 2.4.4测试使用spring安全代码的权限

时间:2015-08-02 15:58:54

标签: unit-testing testing grails-2.0 spock

我正在使用spock进行应用程序测试并使用Grails 2.4.4。我已完成域,控制器和服务单元测试。但在控制器部分,我坚持使用角色明智的访问。对于身份验证,我使用的是Spring Security Core Plugin。以下是我的示例代码。

@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以访问索引操作?

1 个答案:

答案 0 :(得分:0)

从您的问题来看,听起来您正在尝试测试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
}