我在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
没有运气。
当然,这个简化的例子可以通过单元测试来处理,但我面临的真实案例需要进行集成测试,因为涉及数据持久性。
答案 0 :(得分:2)
myBeanMock.beanMethod(_) >> 'foo'
需要一个参数。
您可以使用
myBeanMock.beanMethod() >> 'foo'
或
myBeanMock.beanMethod(*_) >> 'foo'
。
无论是哪种情况,模拟都不应该是Integration规范的一部分,因为这是一个集成测试。在您解释的情况下,可能需要。