Spring integration testing with Spock

I'm currently working on a project where we use Spring Framework 4.0 and Spock for testing. Unit testing in Spock is really great, but there are some lacks in integration testing - especially in mocking Spring beans. Our requirement is to start up Spring context but with particular bean replaced with mock.

The easiest part we had do implement is just regular Spring test specification:

        classes = [GatewayConfig, PaymentServiceConfig])
class PaymentServiceSpecIT extends Specification {

  final String CLIENT_ID = "54321"

  PaymentService paymentService

  def "Should return auth token"() {
            def token = paymentService.getAuthToken(CLIENT_ID)


The problem here is that getAuthToken method have to find this client configuration (including for example some keys data). It's done by invoking configurationService.getClientConfig(CLIENT_ID) method. So the best option here is to mock this invocation and return some predefined fixture.

What comes on my mind in that moment is Springockito project. Due to JavaConfig is our application springockito-annotations module have to be used. After adding proper dependency you just need to add "loader = SpringockitoAnnotatedContextLoader" into @ContextConfiguration.

And last but not least part - setting up mock. After many tries it was impossible for me to drive Spock mocking framework to do that, so I come back to old-school Mockito. Finally my test class looks as follows:

        classes = [GatewayConfig, PaymentServiceConfig],
        loader = SpringockitoAnnotatedContextLoader)
class PaymentServiceSpecIT extends Specification {

  final String CLIENT_ID = "54321"

  PaymentService paymentService

  ConfigurationService configService

  def "Should return auth token"() {
      def token = paymentService.getAuthToken(CLIENT_ID)


And that leads our test to working properly :)


dsrini.open said…
How did you setup the contextconfig, the other files. Is it through spring beans xml file ? Can you show that configs ?
Unknown said…
Spring configuration is done by normal @Configuration classes and there is nothing specific related to tests
pbetkier said…
Helpful post, integrating Spring, Spock and Springockito can be tricky.

It's worth noting that there is a pitfall when integrating Spock and Spring Boot with implicit property sources (application.properties etc.). In order to get them loaded in the first example (without Springockito), we should additionally specify "loader = SpringApplicationContextLoader" in @ContextConfiguration. In the second example, with Springockito, we cannot do that since we need a SpringockitoAnnotatedContextLoader, but adding "initializers = ConfigFileApplicationContextInitializer" to @ContextConfiguration solves the problem.

Alternatively, we could define our property sources explicitly in our JavaConfig e.g. using @PropertySource("application.properties") and leave @ContextConfigurations as presented.

Do you have a better suggestion on how to overcome this pitfall?
Unknown said…
IMHO as long as Spock doesn't support meta-annotations there is no better solution for that
Karol Kuc said…
Why not just
ConfigurationService mockedConfiguratinService(){
ConfigurationService cs = Mock()
in a configuration class?
Unknown said…
The problem with Spock mocks is that when you want to verify them it needs to be in the same line as setup. But I currently use constructions you've posted with Mockito, however the initialization is done in the particular test, because I don't like to keep mocking separately from test. That causes the problem that you have to remember what is a mock and what is not. It's easy when you're mocking whole layers (as described here: http://www.kubrynski.com/2015/11/smart-package-structure-to-improve.html)
Unknown said…
Hello Jakub,
The Article on Spring integration testing with Spock is amazing give detail information about it .Thanks for Sharing the information about Integration Testing.
Software Testing Company
suvathi said…
Such an awesome article, these many days, doubts in multiple concepts were bothering me, I started searching through books and net, but doubt was not cleared, thank you so much for providing this article, helped me a lot
software testing training in chennai
Naveen S said…
Pretty blog, so many ideas in a single site, thanks for the informative article, keep updating more article.
Software testing course in chennai
Nice post. Thanks for sharing! I want people to know just how good this information is in your article. It’s interesting content and Great work.
Thanks & Regards,
VRIT Professionals,
No.1 Leading Web Designing Training Institute In Chennai.

And also those who are looking for
Web Designing Training Institute in Chennai
SEO Training Institute in Chennai
Photoshop Training Institute in Chennai
PHP & Mysql Training Institute in Chennai
Android Training Institute in Chennai
Rigid Box said…
Excellent Blog. I really want to admire the quality of this post. I like the way of your presentation of ideas, views and valuable content. No doubt you are doing great work. I’ll be waiting for your next post. Thanks .Keep it up!
Kindly visit us @
Luxury Boxes
Premium Packaging
Luxury Candles Box
Earphone Packaging Box
Wireless Headphone Box
Innovative Packaging Boxes
Wedding gift box
Leather Bag Packaging Box
Cosmetics Packaging Box
Luxury Chocolate Boxes
adhi said…
thanks for your information really good and very nice web design company in velachery
zuan said…
Thanks for sharing an informative blog keep rocking bring more details.I like the helpful info you provide in your articles. I’ll bookmark your weblog and check again here regularly. I am quite sure I will learn much new stuff right here! Good luck for the next!
web designing classes in chennai | web designing training institute in chennai
web designing and development course in chennai | web designing courses in Chennai
best institute for web designing in chennai | web designing course with placement in chennai
Nannie Co Pam said…
Great Article. Thank you for sharing! Really an awesome post for every one.

IEEE Final Year projects Project Centers in Chennai are consistently sought after. Final Year Students Projects take a shot at them to improve their aptitudes, while specialists like the enjoyment in interfering with innovation. For experts, it's an alternate ball game through and through. Smaller than expected IEEE Final Year project centers ground for all fragments of CSE & IT engineers hoping to assemble. Final Year Project Domains for IT It gives you tips and rules that is progressively critical to consider while choosing any final year project point.

Spring Framework has already made serious inroads as an integrated technology stack for building user-facing applications. Spring Framework Corporate TRaining the authors explore the idea of using Java in Big Data platforms.
Specifically, Spring Framework provides various tasks are geared around preparing data for further analysis and visualization. Spring Training in Chennai
Hello Admin!

Thanks for the post. It was very interesting and meaningful. I really appreciate it! Keep updating stuffs like this. If you are looking for the Advertising Agency in Chennai | Printing in Chennai , Visit Inoventic Creative Agency Today..
Anonymous said…
Great efforts put to publish these kinds of articles that are very useful to know. I’m thoroughly enjoying your blog. And Good comments create great relations. You’re doing an excellent job. Keep it up.

Magento Development Training Course in Chennai Zuan Education

Selenium Training Course in Chennai Zuan Education

John Loomer said…
Forex Signals, MT4 and MT5 Indicators, Strategies, Expert Advisors, Forex News, Technical Analysis and Trade Updates in the FOREX IN WORLD

Forex Signals Forex Strategies Forex Indicators Forex News Forex World
Elina Sam said…

DigiPeek is the best SEO & Link Building Service Provider In The World. I have 7+ Years Experience To Build SEO, Backlinks & Improve Website Ranking.

If you need Profile Backlinks, Forum Backlinks, Dofollow Backlinks, Manual Backlinks, Trusted SEO Backlinks, Increase Domain Rating Then You Will Contact Me.

I am glad to help You!

Let's TRY!
Shield Security Solutions Provides Ontario Security Training, Security Guard License or Security License in Ontario. Get Started Today
power said…
To begin, if you have not installed the Python interpreter on your system, now is the time. To make that step easier, install the latest Python distribution using packages compatible with your Linux distribution. rpm, deb and tgz are also available on your Linux CD-ROM or on-line. unindent does not match any outer indentation level
Brandstory said…
Nice post really interesting article. we are the leading ui ux company and ui ux designers
Shoppa.in said…
I am impressed. I don't think I've met anyone who knows as much about this subject as you do. You are truly well informed and very intelligent. You wrote something that people could understand and made the subject intriguing for everyone. Really, great blog you have got here.
B2B Marketplace
Our Service Partners
Refrigerator Repair Service
Satta King
Mumbai Call Girls
Danny James said…
Take a look at Best Indoor Playground Los Angeles For Kids to have fun and enjoyable with them.
Mike Johnson said…
I wish you good luck in your project, I like it, so I decided to help you. I have many followers in twitter, so I share this article there and buy twitter likes from this site https://soclikes.com/
Quikads said…
So informative. I was searching like this for a few days. Thank you for sharing this information.
second hand mobile phones for sale
When you think Indonesia, you probably picture its Labuan Bajo, and sunny beaches in Canggu. Yet, many people don’t realize that Indonesia is also a great place to start a business. According to International Labour Organization, there are about 700 thousand small businesses in Indonesia in 2018, which 57 million are small and medium sized enterprises Start Business in Indonesia

But what makes Indonesia so great? Major cities like Jakarta, Bandung, Yogyakarta, and Surabaya, an impressive university system, and low taxes means the Sunshine country is ripe with opportunity for savvy business owners. Keep reading to learn more about why Indonesia could be the perfect spot to start your new business!
SEO adalah proses meningkatkan visibilitas dan peringkat website bisnis Anda di laman hasil penelusuran mesin telusur, seperti Google, Bing, dan Yahoo, sehingga memudahkan pelanggan menemukan produk atau layanan Anda secara online.

Kami menawarkan layanan Jasa SEO terbaik di Bali dengan Strategi Optimasi Situs Website secara tepat dan akurat sesuai dengan prinsip kerja mesin pencari.
Satya Puri Studio is Bali architects have worked on historically-inspired homes & villa around the world — including “Lux Villa in Bali; Sukh Sagar Haveli in Jodhpur, Rajasthan; Kahani Paradise in Gokarna. Their work shows inspiration across history and styles, tied together with the goal of enhancing life through good design. Above all, Satya Puri Studio Architects aims to produce personalized living environments.
Website Developer Bali adalah seorang Freelancer Website Developer Bali, dia sangat menyukai hobbynya dalam menelusuri setiap blok yang Anda di internet. Dia memiliki banyak pengetahuan tentang Digital Marketing dan bagaimana penerapan dalam bisnis.
Kami adalah salah satu media Info Kerja Bali online terkemuka di Bali.
Membantu memfasilitasi pencocokan dan komunikasi peluang kerja antara pencari kerja dan pemberi kerja, di Bali, Denpasar, Legian, Seminyak, Canggu, Sanur, Nusa Dua, Tuban, Jimbaran.
GoProtoz said…
Nice blog has been shared by you. before i read this blog i didn't have any knowledge about this but now i got some knowledge so keep on sharing such kind of an interesting blogs.
UI UX Design Studio
ji jhon 88 said…
The major reason for phenomenal grown of IT in Hyderabad has been the development of infrastructure collectively called as HITEC City, which encouraged many IT companies to set up operations in the city. Salesforce Training in Hyderabad
Jasonsmith said…
Such a useful blog with required information. Thanks for sharing this amazing blog.
AWS Training in Chennai
DevOps Training in Chennai
aaronnssd said…
You've supplied us with an interesting article. This is a fantastic resource for expanding your understanding of the subject Software testing Service Provider Noida Uttar Pradesh. Thank you very much.
Gorish dua said…
Thanks for sharing.
We at Antino Labs believe in redefining and refining our model to suit the industry's requirements. Antino Labs' several years of experience in the market has let us register our global presence. Antino Labs' has the vision to become the world's most trusted partner for digital transformation and we aim to become a brand that defines innovation and the latest technology. We offer clients a one-stop solution for all their interests regarding IT consulting services in Gurgaon and UI/UX design services in Gurgaon.
Very Informative and useful... Keep it up the great work. I really appreciate your post.

토토사이트 said…
I've been searching for hours on this topic and finally found your post. 바카라사이트, I have read your post and I am very impressed. We prefer your opinion and will visit this site frequently to refer to your opinion. When would you like to visit my site?

Gorish dua said…
We at Antino Labs believe in redefining and refining our model to suit the industry's requirements. Antino Labs' several years of experience in the market has let us register our global presence. Antino Labs' has the vision to become the world's most trusted partner for digital transformation and we aim to become a brand that defines innovation and the latest technology. We offer clients a one-stop solution for all their interests regarding Application building and Web development.
Web Development Services in Gurgaon
ihsltd said…
Thanks for the blog, Its good and valuable information.
IT Support Services London
Enga Doctor said…
Thanks for posting. Useful information.

Introducing a new application named Engadoctor. Especially design with newly emerging technology for Online Doctor Consultation & Book Online Doctor Appointment.

Popular posts from this blog

Using jstat to report custom JVM metric sets

Understanding Spring Web Initialization

Including Java agent in standalone Spring Boot application