Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

spring - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 */ }.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...