如何在grails中为服务编写spock测试?
我在如何在grails中为服务编写spock测试?,grails,spock,Grails,Spock,我在grails-app/services/com/myapp/ 该服务有一个方法: boolean spockTest() { return false; } 我已经在我的BuildConfig.groovy test(":spock:0.7") { exclude "spock-grails-support" } 问题 我应该如何/在哪里为此服务编写spock测试 我将如何运行它 简单的服务: // grails-app/services/com
grails-app/services/com/myapp/
该服务有一个方法:
boolean spockTest() {
return false;
}
我已经在我的BuildConfig.groovy
test(":spock:0.7") {
exclude "spock-grails-support"
}
问题
- 我应该如何/在哪里为此服务编写spock测试李>
- 我将如何运行它
- 简单的服务:
// 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测试应用单元:
运行测试
您没有提到您正在使用的Grails版本。使用2.4.0,您不需要在BuildConfig.groovy中提到Spock,就可以让它正常工作 您的服务方法中没有做任何事情,您可以按如下方式进行测试
@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"
}
}
其中Comment是我的域类
我以grails测试应用程序-unitmySampleServiceSpec的形式运行这个测试。你应该能够很容易地编写一个。你真的不应该在Spock规范中使用这样的断言。在
中,然后:
块而不是断言结果。comment==“My comment”
通常要做的事就是结果。comment==“My comment”
。你的注释是grails测试应用程序单元
。我的意思是grails测试应用程序单元:
。你是在评论中省略了冒号,还是你实际运行的是冒号?如果没有冒号,我不希望这样做。当我添加那条时,你的评论消失了。这里有一条评论说该命令不起作用,它引用了grails test-app-unit
作为输入的命令。我使用的是grails 2.2.4。按照你的回答,我的测试仍然没有执行。尝试了以下grails测试应用程序单元:
grails测试应用程序单元:spock
和grails测试应用程序:spock
,但使用所有三个我得到的消息测试都通过了
,但报告显示未执行任何测试
。我甚至故意让测试失败,但它说测试通过了,因为它们从来没有运行过……对不起,我有很多评论,然后我删除了它们,添加了一条评论来解释我所做的一切。感谢您的帮助我刚刚创建了一个2.2.4应用程序,并将这些类直接从浏览器粘贴到项目中,测试工作正常。请参阅其中包括服务的Spock规范和JUnt测试。如果运行grails测试应用程序unit:
测试将运行并通过。如果在测试中更改断言或更改服务代码,测试将失败。