Grails 2.4.4 Testing for permission where spring security code is being used

房东的猫 提交于 2019-12-05 18:32:02

From your question, it sounds like you are trying to test whether the Spring Security code is working. My take on unit testing controllers is that 'if I didn't write I'm not testing it.' Services used by my controllers are mocked, configuration values used by my controller are mocked. Likewise, Spring Security behaviors are mocked (in effect). This means accepting some amount of risk related to the plugins that you use in your application. Do you trust Spring Security to handle roles and authorities correctly? I generally do.

I'm more interested in the behaviors of my code, so I generally just bypass the spring check in my Unit tests. If you want to verify the behaviors of your application if the user is or is not logged in, or does or does not have a certain role, you can do that.

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
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!