Saturday 13 September 2014

Spring MVC Test cases with Annotated Beans Using Mockito

Annotations make java developer's life easy and also it feels like annotation based classes are complex for unit testing. But in reality it is quite simple. There are couple of ways through which you can test autowired/spring based classes.

Method 1:
You can use AnnotationConfigApplicationContext to load application context. Instantiate application context, register annotated classes and test your methods. Here is the sample code

Method 2:
Even though preceding method is an easiest way to test annotation based spring classes, if your test case becomes complex and if you want to mock actual request etc, you better move to mocking framework instead of basic one. I have used mockito with spring-test to mock actual requests with spring beans. Here is the sample code

In the above sample code we have used spy to mock real objects, if you just want to mock it you can use mock annotation instead of spy.

For this you need mockito and spring-test jars. Following are the minimal poms for the both respectively.
     <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
            <version>1.9.5</version>
            <scope>test</scope>
  </dependency>
            <dependency>
           <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.0.0.RELEASE</version>
          <scope>test</scope>
  </dependency>

Here is the complete code with both the testing methodologies.
spring-test-template using mockito

No comments:

Post a Comment