如何使用Spock和Grails 2模拟服务方法的接口参数?

时间:2017-05-29 23:57:32

标签: grails spock

给出类似的东西:

@TestFor(MyService)
@Mock(SomeClass)
class WhateverSpec extends Specification {
  def 'Test a mock'() {
    given:
    def someObject = new SomeClass(name: 'hello')
    assert someObject.name == 'hello'

    when:
    def result = service.doSomething(someObject)

    then:
    result == 'nice'
  }
}

鉴于doSomething()被定义为:

String doSomething(SomeClass thing) {
  // ...
  return 'nice'
}

应该没有问题。但是如果doSomething中的参数是界面怎么办? String doSomething(SomeInterface thing)。如何在不直接创建新SomeClass的情况下在测试中创建模拟对象(就像我不应该假设它将是什么类型的对象,但该对象肯定会实现接口)。

1 个答案:

答案 0 :(得分:1)

你可以使用规范中的Mock / Stub / Spy方法(取决于你的需要)

def mokedInterface = Mock(MyInterface)

这是一个带有模拟List接口的例子:

def 'should mock List interface size method'() {
    given:
        def mockedList = Mock(List)
        def expectedListSize = 2
        mockedList.size() >> expectedListSize
    when:
        def currentSize = mockedList.size()
    then:
        currentSize == expectedListSize
}
相关问题