nbkhope
nbkhope

Reputation: 7474

How to mock an interface parameter for a service method using Spock and Grails 2?

Given something like:

@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'
  }
}

Given doSomething() is defined as something like:

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

There should be no problem. But what if the parameter in doSomething is an interface? String doSomething(SomeInterface thing). How would I go about making a mock object in the test without directly creating a new SomeClass (like I am not supposed to assume what kind of object it will be, but that object will certainly implement the interface).

Upvotes: 1

Views: 4745

Answers (1)

rgrebski
rgrebski

Reputation: 2584

You can use Mock/Stub/Spy method from Specification (depends on your needs)

def mokedInterface = Mock(MyInterface)

Here is an exmple with mocking List interface:

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
}

Upvotes: 2

Related Questions