Grails Spock Mock在单元测试中注入服务

时间:2016-05-10 09:15:50

标签: unit-testing grails mocking spock

如何使用Spock在Grails UnitTest(规范)中注入其他服务?

class ServiceOne {

   ServiceTwo serviceTwo

    ModelOne getMethodOne(String name) {
       // do somethings here
       return serviceTwo.getMethodTwo(name)
    }
}

class ServiceTwo {

   ServiceTwo serviceTwo

    ModelOne getMethodTwo(String name) {
       // do somethings here
       return ModelOne.get(name)
    }
}

// Tests
import grails.test.mixin.Mock
import grails.test.mixin.TestFor
import spock.lang.Specification
/**
 * Tests for ServiceOne
 */
@TestFor(ServiceOne)
@Mock(ModelOne)
class ServiceOneSpec extends Specification {
/** Inject serviceTwo in here
    Otherwise the following exception is thrown
    java.lang.NullPointerException: Cannot invoke method getMethodTwo() on null object
*/

void "test method one"() {

    when:
    ModelOne modelOne = service.getMethodOne(name)

    then:
    modelOne != null
   }
}

2 个答案:

答案 0 :(得分:0)

离开我的头顶,这应该让你开始。

@TestFor(ServiceOne)
@Mock(ModelOne)
class ServiceOneSpec extends Specification {

   void "test method one"() {
      given:
         def mockServiceTwo = mockFor(ServiceTwo)
         // expect that getMethodTwo is called once
         mockServiceTwo.demand.getMethodTwo(1) { String name ->
            // for any arbitrary name value, return a new ModelOne
            return new ModelOne()
         }
         service.serviceTwo = mockServiceTwo.createMock()
      when:
         ModelOne modelOne = service.getMethodOne(name)

      then:
         modelOne != null
   }
}

答案 1 :(得分:0)

这就是我解决问题的方法 - 通过创建服务的对象(它不是单例,但它很好,因为它只是用于单元测试)

// Test Spec
import grails.test.mixin.Mock
import grails.test.mixin.TestFor
import spock.lang.Specification
/**
 * Tests for ServiceOne
 */
@TestFor(ServiceOne)
@Mock(ModelOne)
class ServiceOneSpec extends Specification {

    @Shared ModelOne modelOne
    def setup() {
        // the magic
        service.serviceTwo = new ServiceTwo()
        modelOne = service.serviceTwo.getMethodTwo("Name")
    }

    void "test method one"() {

        when:
        ModelOne modelOne = service.getMethodOne(name)

        then:
        modelOne != null
   }
}