Grails,Integration Testing,在使用Spock测试服务时模拟bean方法

时间:2015-05-25 14:29:18

标签: grails integration-testing spock

我在Grails 2.4.5中执行集成测试时遇到问题。

我想测试的服务如下:

class MyService {

    def myBean

    def serviceMethod() {
        myBean.beanMethod()
    }
}

myBean中定义了resources.groovy

beans = {
    myBean(MyBeanImpl)
}

这是集成测试:

MyServiceIntegrationSpec extends IntegrationSpec {

    def myService

    def setup() {
        def myBeanMock = Mock(MyBeanImpl)
        myBeanMock.beanMethod(_) >> 'foo'
        myService.myBean = myBeanMock
    }

    void "silly test"() {
        expect: 
        myService.serviceMethod() == 'foo'
    }
}

好吧,自myService.serviceMethod()返回null以来,这种情况严重失败。

我已经尝试了

ReflectionTestUtils.setField(myService, 'myBean', myBeanMock)

而不是

myService.myBean = myBeanMock

没有运气。

当然,这个简化的例子可以通过单元测试来处理,但我面临的真实案例需要进行集成测试,因为涉及数据持久性。

1 个答案:

答案 0 :(得分:2)

myBeanMock.beanMethod(_) >> 'foo'需要一个参数。

您可以使用

myBeanMock.beanMethod() >> 'foo'

myBeanMock.beanMethod(*_) >> 'foo'

无论是哪种情况,模拟都不应该是Integration规范的一部分,因为这是一个集成测试。在您解释的情况下,可能需要。