How to test Grails service using Spock?

后端 未结 2 2001
无人共我
无人共我 2021-02-14 11:39

I have a EncouragementService.groovy with following method

  class EncouragementService {
   def stripePaymentService 

   def encourageUsers(List&l         


        
相关标签:
2条回答
  • 2021-02-14 12:00

    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 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>
      }
    }
    
    0 讨论(0)
  • 2021-02-14 12:21

    Use the build-test-data plugin to build the users.

    @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()]
      }
    }
    

    I've also made a couple of changes to the code to make it a proper spock specification. Your test has to extend Specification and you might want to familiarize yourself with Spock's keywords.

    0 讨论(0)
提交回复
热议问题