如何使用Spock测试Grails服务? [英] How to test Grails service using Spock?
问题描述
我有一个 EncouragementService.groovy
以下方法
I have a EncouragementService.groovy
with following method
class EncouragementService {
def stripePaymentService
def encourageUsers(List<User> users){
if(null != users && users.size()>0){
for(User user : users){
//logic
stripePaymentService.encourage(user)
//
}
}
}
}
要在JAVA中测试以上代码,使用JUnit I将首先创建两个或三个用户在设置。将用户列表传递给>鼓励用户(...)
方法,并检查我想要的结果。
To test above code in JAVA universe, using JUnit I would first create two or three users in setup. Pass the list of users to encourageUsers(...)
method and check whatever I want with the result.
我怎么能在grails中实现同样的事情呢?
How can I achieve the same thing here in grails,
import com.github.jmkgreen.morphia.Datastore;
@TestFor(EncouragementService)
class EncouragementServiceSpec {
def morphiaService = new MorphiaService()
void testEncourageUsers() {
List<User> users = createUsers();
encouragementService.(users)
//
}
def createUsers(){
Datastore datastore = morphiaService.dataStoreInstance()
def user = new User()
user.setName("Prayag Upd")
//
datastore.save(user)
[user]
}
}
我使用 spock:0.7
plugins {
test(":spock:0.7") { exclude "spock-grails-support" }
}
推荐答案
Service类可以优化如下:
Service class can be optimized as below:
class EncouragementService {
def encourageUsers(List<User> users){
if(users){ //Groovy truth takes care of all the checks
for(user in users){
//logic
}
}
}
}
Spock单元测试:
Spock将测试带到另一个级别,您可以在其中测试行为(遵守BDD)。测试类将如下所示:
Spock Unit Test:
Spock takes testing to whole another level, where you can test the behavior (adheres to BDD). The test class would look like:
import spock.lang.*
@TestFor(EncouragementService)
@Mock(User) //If you are accessing User domain object.
class EncouragementServiceSpec extends Specification{
//def encouragementService //DO NOT NEED: mocked in @TestFor annotation
void "test Encourage Users are properly handled"() {
given: "List of Users"
List<User> users = createUsers()
when: "service is called"
//"service" represents the grails service you are testing for
service.encourageUsers(users)
then: "Expect something to happen"
//Assertion goes here
}
private def createUsers(){
return users //List<User>
}
}
这篇关于如何使用Spock测试Grails服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!