4

我有一个非常简单的单元测试来测试将当前用户呈现为 JSON 的控制器操作。这是我的测试课:

@TestFor(UserController)
class UserControllerSpec extends Specification {

    def setup() {
        def springSecurityService = mockFor(SpringSecurityService)
        springSecurityService.demand.getCurrentUser { -> [name: "Jim"] }
        controller.springSecurityService = springSecurityService.createMock()
    }

    def cleanup() {
    }

    void "test current"() {
        when:
        request.method = 'GET'
        controller.current()

        then:
        response.json.name == "Jim"
    }
}

这是控制器(省略无关代码)

def springSecurityService

static responseFormats = ['json']

static allowedMethods = [current: "GET"]

def current() {
    respond(springSecurityService.currentUser)
}

我正在单独执行这个测试grails test -unit package.class,它通过命令行工作:

|Running 1 unit test... 1 of 1
|Completed 1 unit test, 0 failed in 0m 11s
.
|Tests PASSED - view reports in ...\target\test-reports

这不适用于 IntelliJ,因为springSecurityService.currentUser它始终为空。这是产生的异常:

org.codehaus.groovy.grails.web.converters.exceptions.ConverterException: Error parsing JSON
    at grails.converters.JSON.parse(JSON.java:292)
    at org.codehaus.groovy.grails.plugins.testing.AbstractGrailsMockHttpServletResponse.getJson(AbstractGrailsMockHttpServletResponse.groovy:97)
    at massemailsystem.UserControllerSpec.test current(UserControllerSpec.groovy:28)
Caused by: org.codehaus.groovy.grails.web.json.JSONException: Missing value. at character 0 of 
    at org.codehaus.groovy.grails.web.json.JSONTokener.syntaxError(JSONTokener.java:470)
    at org.codehaus.groovy.grails.web.json.JSONTokener.nextValue(JSONTokener.java:357)
    at grails.converters.JSON.parse(JSON.java:283)
    ... 2 more

有任何想法吗?

4

1 回答 1

1

您需要在 IntelliJ 中将此测试用例作为 grails 测试用例运行。 在此处输入图像描述 在此处输入图像描述

于 2014-12-22T22:47:43.237 回答