0
votes

I've been using Spock for unit testing, and it's great, but I've got some legacy code that creates Mockito mocks, and any specifications that use this legacy code must fall back to using Mockito operations such as when and verify.

For example:

public class FooSpec extends Specification {

  def "services invoked when something happens"() {
    given: "legacy code that creates mock services that are Mockito mocks"
    ServiceFactory serviceFactory = new MockitoServiceFactory()

    and: "a foo instance"
    def foo = new Foo()

    and: "the foo instance is configured with a service that is a Mockito mock"
    foo.service = serviceFactory.getService("foo")

    when: "the foo instance sends an event"
    foo.sendEvent()

    then: "the foo service actually sends the event"
    verify(foo.service, times(1)).sendEvent() || true
  }
}

I would much rather do this verification the Spock way:

  1 * foo.service.sendEvent()

This is an overly simplistic example, but is there any way to wrap a Mockito mock object so that it behaves like a Spock mock object? I thought about creating a SpockServiceFactory that generates Spock mock objects, but I recalled that Spock does not allow mocks to be created outside of specifications (maybe this has changed?)

1
Can You please provide a runnable example - with @Grab annotation for dependencies? I'd like to have a try but have problems setting it all up. - Opal

1 Answers

0
votes

There is no way (without forking the Spock codebase) to verify a Mockito mock using Spock's mocking syntax.

but I recalled that Spock does not allow mocks to be created outside of specifications (maybe this has changed?)

It hasn't changed yet (base class is currently the closest you can get).