我在我的圣杯申请中使用shiro安全。 Grails版本:2.2.1 shiro:1.2.0
我在为启用过滤器的控制器编写grails单元测试用例时遇到问题。当测试用例在没有过滤器的情况下运行时它工作正常,如果它运行withFilters,那么它在控制器中找不到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"
}
}
答案 0 :(得分:0)
尝试使用:
ControllerOrService.metaClass.method = {
return "" //what you need to be returned
}
如果方法采用参数,则将参数添加到闭包中:
ControllerOrService.metaClass.method = { def a, def b ->
return a + b
}
当你以这种方式嘲笑时,不要忘记使用方法的全名。