Monday, 12 August 2013

Integration Tests, Spring and Mocking

Sometimes ago, I emphasised how much integration tests were needed? This time I will show some tricks to build nice integration tests. This use case specific to Spring Framework, however can be applied to similar scenarios.
That trick is about using Spring Framework and Mockito to build integration tests and mock behaviours of the dependencies. The mocks are not data mocks but dependency mocks. Data mocks are a little bit different than dependency mocking as the previous one allows generating/injecting data for the mock on the wire, while the latter one mocks library dependencies.
Today’s software are getting more interacted and communication with a number of services and systems. For example a service could use a messaging server to receive and send messages to the interested parties through a messaging exchange. That strategy enables achieving abstracted systems. Similarly applications can be built with abstracted components so that an individual component can be tested in isolation while it is dependencies are mocked with different strategies. Testing individual components helps reducing some heavy weight functional tests and ensuring components are reliable to some degree.
Below code samples demonstrates building integration tests with Spring and Mockito, notice the code line mocking a spring bean.

Spring Factory & Mockito

This nice spring feature is a kind of hidden gem, maybe because of its a bit confusing "constructor-arg" naming. That parameter sounds like class constructor argument, however in reality it can be used for any method argument.

Spring Context

And here is the spring test context including main application context and abstracted test dependency. Separating spring context into multiple chunks helps building abstracted systems and allows plugging a mocked dependency into an integration test.

1 comment:

  1. Hello,
    The Article on Integration Tests, Spring and Mocking is informative. It gives detailed information about it .Thanks for Sharing the information on Software Integration Testing.
    Software Testing Services