单元测试在Intellij 13中失败但通过命令行传递

时间:2014-05-21 19:28:26

标签: unit-testing grails intellij-idea spock intellij-13

我有一个非常简单的单元测试,用于测试将当前用户呈现为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

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您需要在IntelliJ中将此测试用例作为grails测试用例运行。 enter image description here enter image description here