如何在grails中为服务编写spock测试?

时间:2014-06-19 17:13:35

标签: grails spock

我在MySampleservice.groovy

中有一个名为grails-app/services/com/myapp/的服务的grails应用程序

该服务有一个方法:

boolean spockTest() {
    return false;
}

我已在BuildConfig.groovy

中添加了此内容
    test(":spock:0.7") {
        exclude "spock-grails-support"
    }

问题

  • 我应该如何/在哪里为此服务编写spock测试?
  • 我该怎么办呢?

2 个答案:

答案 0 :(得分:0)

一项简单的服务:

// grails-app/services/com/myapp/MySampleService.groovy
package com.myapp

class MySampleService {

    def someMethod(String arg) {
        arg?.toUpperCase()
    }
}

该服务的Spock规范:

// test/unit/com/myapp/MySampleServiceSpec.groovy
package com.myapp

import grails.test.mixin.TestFor
import spock.lang.Specification

@TestFor(MySampleService)
class MySampleServiceSpec extends Specification {

    void "test someMethod"() {
        expect:
        service.someMethod(null) == null
        service.someMethod('Thin Lizzy') == 'THIN LIZZY'
    }
}

您可以使用grails test-app unit:运行测试。

您没有提到您正在使用的Grails版本。使用2.4.0,您无需在BuildConfig.groovy中提及Spock,以便使其正常工作。

答案 1 :(得分:0)

您的服务方法没有做任何事情,您可以将其作为

进行测试
@TestFor(MySampleService)
class MySampleServiceSpec extends Specification {

    def setup() {
    }

    def cleanup() {
    }

    void "test something"() {
        when:
        def result = service.spockTest()

        then:
        assert result == false
    }
}

服务一般用于数据库交互,比如保存数据,让我们举一个简单的例子,以下是我的服务方法

Comment spockTest(String comment) {
    Comment commentInstance = new Comment(comment: comment).save()
    return commentInstance
}

然后我通常将其测试为

@TestFor(MySampleService)
@Mock([Comment])
class MySampleServiceSpec extends Specification {

    def setup() {
    }

    def cleanup() {
    }

    void "test something"() {
        given:
        Integer originalCommentCount = Comment.count()

        when:
        def result = service.spockTest('My Comment')

        then:
        assert originalCommentCount + 1 == Comment.count()
        assert result.comment == "My Comment"
    }
}

评论是我的域类。

我将此测试作为grails test-app -unit MySampleServiceSpec

运行
相关问题