如何使用Spock测试Grails服务?

时间:2013-09-05 19:40:30

标签: java unit-testing grails groovy spock

我有EncouragementService.groovy以下方法

  class EncouragementService {
   def stripePaymentService 

   def encourageUsers(List<User> users){
     if(null != users && users.size()>0){
      for(User user : users){
        //logic
        stripePaymentService.encourage(user)
        //
      }
     }   
   }
  }

要在JAVA Universe中测试上面的代码,使用JUnit我首先会在setup中创建两个或三个用户。将用户列表传递给encourageUsers(...)方法,并根据结果检查我想要的内容。

如何在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" }
}

2 个答案:

答案 0 :(得分:13)

服务类可以优化如下:

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)。测试类看起来像:

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>
  }
}

答案 1 :(得分:4)

使用build-test-data plugin构建用户。

@TestFor(EncouragementService)
@Build(User)
class EncouragementServiceSpec extends Specification {

  def "encourage users does x"() {
    given:
    def users = createUsers();

    when:
    service.encourageUsers(users)  

    then:
    // assert something
  }

  def createUsers(){
    [User.build(), User.build(), User.build()]
  }
}

我还对代码进行了一些更改,以使其成为正确的spock规范。您的测试必须扩展规范,您可能希望熟悉Spock's keywords