5

我为我的项目使用了 Grails Spring Security 插件,现在想要对我的代码进行单元测试。我的控制器中有以下代码:

def index() {
    redirect action: 'show', params: [id: springSecurityService.currentUser.id]
}

我的测试类有以下代码:

void testIndex() {      
    controller.index()
    assert "/user/list" == response.redirectedUrl
}

此测试失败:

| 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)

如何在测试用例中验证 Spring Security 用户?您将如何编写单元测试?

4

3 回答 3

7

您必须使用功能测试来确保安全。单元测试使用模拟但没有可用的插件或真正的请求。Spring Security 是使用过滤器链实现的,因此您需要一个真正运行的服务器。如果你使用模拟,你只是在测试模拟。

于 2012-10-09T19:37:56.263 回答
4

对于这么简单的事情,我不会为复杂的模拟而烦恼,一个简单的

controller.springSecurityService = [currentUser:[id:1]]

就足够了。

于 2012-10-09T19:37:19.853 回答
0

您的引用似乎springSecurityService为空。只要您的控制器中有一个名为 的字段springSecurityService,就应该注入它。您是否仅在索引方法中将其用作局部变量并且没有将其声明为字段?

UserController的如下:

class UserController {

    /**
     * Dependency injection for the springSecurityService.
     */
    def springSecurityService

    ....
 }

更新

根据您对此答案的评论,您确实springSecurityService在控制器中声明了一个字段。我拿了我的工作应用程序并尝试了一个测试,该测试用我的控制器方法反映了你的应用程序:

@TestFor(UserController)
class UserControllerTests {

    void testSomething() {
        controller.register()
    }
}

我也得到了 NullPointerException。根据 Burt 的回答,(我不知道),我认为该springSecurityService实例在单元测试执行的上下文中为空。

于 2012-10-09T19:34:26.537 回答