Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create Spock mocks outside of a specification class?

We combine Spock tests with Spring's @ContextConfiguration so we can build beans in a spring context and then use Spock for the actual testing. We would like to inject spock mocks into our spring beans. For Mockito there is an extension which allows you to do things like:

 <mockito:mock id="accountService" class="org.kubek2k.account.DefaultAccountService" />

and then reference this mock to other spring beans. There seems to be no such extension for Spock. Then again building this is probably not too much effort if you know how to create Mocks outside of the Specification class. The only way of creating a Spock mock that I'm aware of is:

T Mock(Class<T> type)   

in Specification. Is there some API in Spock to create Mocks when not being inside the Specification class, so I could create Spock mocks for a spring context?

like image 635
Jan Thomä Avatar asked May 29 '13 09:05

Jan Thomä


People also ask

How do you mock a method in Spock?

In Spock, a Mock may behave the same as a Stub. So we can say to mocked objects that, for a given method call, it should return the given data. So generally, this line says: itemProvider. getItems will be called once with ['item-'id'] argument and return given array.

Can you use Mockito with Spock?

We can use Mockito stubbing, not Spock's. It works well! To help you with spock mocks, Spock also has annotations to setup mocks from the Subject Collaborator extension: github.com/marcingrzejszczak/…

What is the difference between mock and stub?

A Mock is just testing behaviour, making sure certain methods are called. A Stub is a testable version (per se) of a particular object.

How do you mock a method in the same class?

Mocking is done when you invoke methods of a class that has external communication like database calls or rest calls. Through mocking you can explicitly define the return value of methods without actually executing the steps of the method.


1 Answers

Creating mocks outside a spec class (and using them in another spec class) isn't currently possible. There's an open feature request for this. It shouldn't be too hard to implement this, but it would require some changes to spock-core. At the very least, there would need to be a way to manually attach a mock object to another spec instance. Probably, it would also make sense to move the user-facing mock creation API out of the MockingApi base class.

You should be able to use Mockito with Spock, as long as you wrap all verification code contained in a then-block with a call to a helper method that returns true (because Spock will consider it an assertion). Something like then: mockito { /* mockito verifications go here */ }.

like image 186
Peter Niederwieser Avatar answered Sep 21 '22 16:09

Peter Niederwieser