2017-05-29 53 views
0

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

@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(就像我不应该假设它会是什么类型的对象,但该对象肯定会实现接口)。

+0

高清interfaceMock =假(SomeInterface) 请参阅http://spockframework.org/spock/docs/1.1/interaction_based_testing.html – rgrebski

+0

@rgrebski为什么你不回答这个问题? ;) – nbkhope

回答

1

您可以使用模拟/存根/间谍法从规范(取决于你的需要)

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 
} 
相关问题