gpt4 book ai didi

unit-testing - 如何在Grails单元测试用例中模拟Shiro accessControl()方法

转载 作者:行者123 更新时间:2023-12-02 14:53:05 24 4
gpt4 key购买 nike

我在grail应用程序中使用了shiro security。
Grails版本:2.2.1
四郎:1.2.0

我在为启用了过滤器的 Controller 编写grails单元测试用例时遇到问题。当测试用例在不使用过滤器的情况下运行时,它可以正常工作;如果在使用Filters的情况下运行,则将导致在 Controller 中找不到accessControl()方法失败。我不知道如何在运行测试用例时使Shiro的api可见。我引用了shiro单元测试用例链接http://shiro.apache.org/testing.html,但无法获得任何有关accessControl()的信息。我给出了示例代码,说明了我的类和测试用例的外观喜欢

MyController.groovy

def create() { 
// getting request parameters and validation
String emailId = params.emailId
def ret = myService.createUser(emailId)

return ret
}

MyControllerFilters.groovy
def filters = { 
loginCheck(controller: 'user') {
before = {
//do some business checks

// Access control by convention.
accessControl() // This is a dynamic method injected by ShiroGrailsPlugin to FilterConfig, but this is not visible during the test case.
}
}

MyControllerTests.groovy
@TestFor(MyController) 
@Mock(MyControllerFilters)
class MyControllerTests {

@Before
void setup() {
// initializing some variables
}

void testCreateUserWithFilter() {

request.accessAllowed = true

withFilters(action:"create") {
controller.create()
}

assert response.message == "success"
}
}

最佳答案

尝试使用:

ControllerOrService.metaClass.method = {
return "" //what you need to be returned
}

如果方法采用参数,则将参数添加到闭包中:
 ControllerOrService.metaClass.method = { def a, def b ->
return a + b
}

以这种方式模拟方法时,请不要忘记使用方法的全名。

关于unit-testing - 如何在Grails单元测试用例中模拟Shiro accessControl()方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18619062/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com