dil*_*dik 5 testing grails unit-testing spring-security
我为我的项目使用Grails Spring Security Plugin,现在想要对我的代码进行单元测试.我的控制器中有以下代码:
def index() {
redirect action: 'show', params: [id: springSecurityService.currentUser.id]
}
Run Code Online (Sandbox Code Playgroud)
我的测试类有以下代码:
void testIndex() {
controller.index()
assert "/user/list" == response.redirectedUrl
}
Run Code Online (Sandbox Code Playgroud)
此测试失败:
| Running 8 unit tests... 1 of 8
| Failure: testIndex(xxx.UserControllerTests)
| java.lang.NullPointerException: Cannot get property 'currentUser' on null object
at xxx.UserController.index(UserController.groovy:12)
at xxx.UserControllerTests.testIndex(UserControllerTests.groovy:19)
Run Code Online (Sandbox Code Playgroud)
如何在测试用例中验证spring security用户?你会怎么写单元测试?
您必须使用功能测试来确保安全性.单元测试使用模拟,但没有可用的插件或实际请求.Spring Security是通过过滤器链实现的,因此您需要一个真正运行的服务器.如果你使用模拟,你只是测试模拟.
您对的引用似乎springSecurityService为空。只要控制器中有一个名为 的字段springSecurityService,就应该注入它。您是否仅在索引方法中将其用作局部变量,而没有将其声明为字段?
我UserController的如下:
class UserController {
/**
* Dependency injection for the springSecurityService.
*/
def springSecurityService
....
}
Run Code Online (Sandbox Code Playgroud)
更新
根据您对此答案的评论,您确实springSecurityService在控制器中声明了一个字段。我使用我的工作应用程序并尝试使用我的控制器方法来反映您的测试:
@TestFor(UserController)
class UserControllerTests {
void testSomething() {
controller.register()
}
}
Run Code Online (Sandbox Code Playgroud)
我也遇到了 NullPointerException。从伯特的回答来看,(我不知道这一点),我认为该springSecurityService实例在单元测试执行的上下文中为空。