Spring Mvc Test

Welcome To Tripathi Spring MVCTest Page

Use Spring MVC Test framework and Mockito to test controllers:

Spring MVC Test framework provides much nicer testing framework to cover many aspects of testing in Spring MVC.   With this framework apart from testing business logic within controllers we can also test inbound/outbound request/response serialization (such as JSON request to Java and Java to JSON response), request mapping, request validation, content negotiation, exception handling and etc.  In order to use it you can add the below dependency into your project POM file

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-test-mvc</artifactId>
  <version>1.0.0.M2</version>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-test-mvc</artifactId>
  <version>1.0.0.BUILD-SNAPSHOT</version>
  <scope>test</scope>
</dependency>
<repository>
   <id>spring-maven-snapshot</id>
   <snapshots><enabled>true</enabled></snapshots>
   <name>Springframework Maven SNAPSHOT Repository</name>
   <url>http://maven.springframework.org/snapshot</url>
</repository>
Add these dependency to pom.xml file

//Pojo
Contract.java 
package com.shiva.test;
public class Contact {
    private Integer id;
    private String firstname,lastname;
    public Contact() {}
    public Contact(Integer id, String firstname, String lastname) {
        this.id = id;
        this.firstname = firstname;
        this.lastname = lastname;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getFirstname() {
        return firstname;
    }
    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }
    public String getLastname() {
        return lastname;
    }
    public void setLastname(String lastname) {
        this.lastname = lastname;
    }
}

//Controller
ContactController .java
@Controller
@RequestMapping(value="shiva")
public class ContactController {
    @RequestMapping("/contact")
    @ResponseBody
    public Contact contact() {
    System.out.println("hiiiiiiiiiiiiii tripatiiiiiiiiii");
        return new Contact();
    }
}


//Test cases
ContactControllerTest .java

package com.shiva.test.Controller;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"file:src/main/webapp/WEB-INF/spring/root-context.xml"})
@WebAppConfiguration
public class MyControllerTest {
private MockMvc mockMvc;
@Autowired
   private WebApplicationContext ctx;
@Before
   public void setUp() {
       this.mockMvc = MockMvcBuilders.webAppContextSetup(ctx).build();
   }
@Test
public void test() throws Exception {
mockMvc.perform(get("/shiva/contact"));

}

}

Note:-
We can test any Relative Rest call by using Sprin mvc test



Steps Follow for SpringMVC TestFramework:
Step 1:
Create the SpringMvcSample Project goto File->New-> Spring Template Project->Spring Mvc Project

Stepe 2 :Create Spring Mvc Junit Test for above Controller of SpringMvcSample
In spring Tool Suite IDE goto the File -> New -> Junit Test Case
create one junit test controller file in src/test/java package

Step 3:
  1. Declare the spring-test-mvc dependency in the pom.xml file.
  2. Add the Spring milestone repository to the pom.xml file.
<repositories>
    <repository>
        <id>spring-milestone</id>
        <name>Spring Portfolio Milestone Repository</name>
        <url>http://repo.springsource.org/milestone/</url>
    </repository>
</repositories>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test-mvc</artifactId>
    <version>1.0.0.M2</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest-library</artifactId>
    <version>1.3</version>
    <scope>test</scope>
</dependency>

Step 4:

Configuring spring-test-mvc

The heart of the spring-test-mvc is a class called MockMvc that can be used to write tests for any application implemented by using Spring MVC. Our goal is to create a new MockMvc object by using the implementations of the MockMvcBuilder interface. The MockMvcBuilders class has four static methods which we can use to obtain an implementation of the MockMvcBuilder interface. These methods are described in following:
  • ContextMockMvcBuilder annotationConfigSetup(Class… configClasses) method must be used when we are using Java configuration for configuring the application context of our application.
  • ContextMockMvcBuilder xmlConfigSetup(String… configLocations) must be used when the application context of our application is configured by using XML configuration files.
  • StandaloneMockMvcBuilder standaloneSetup(Object… controllers) must be used when we want to configure the tested controller and the required MVC components manually.
  • InitializedContextMockMvcBuilder webApplicationContextSetup(WebApplicationContext context) must be used when we have already created a fully initialized WebApplicationContext object.
These configuration methods are described in the following.

Using XML Configuration

MockMvc mockMvc = MockMvcBuilders.xmlConfigSetup("classpath:applicationContext.xml").build();

Using Java Configuration

MockMvc mockMvc = MockMvcBuilders.annotationConfigSetup(ExampleApplicationContext.class).build();

Using Web Application Context

WebApplicationContext wac = …
MockMvc mockMvc = MockMvcBuilders.webApplicationContextSetup(wac).build();
Step 5:
We can configure our integration tests by following these steps:
  1. Use the @RunWith annotation to configure the used test runner. In this case we must use the SpringJUnit4ClassRunner class to run our integration tests.
  2. Use the @ContextConfiguration annotation to configure either the application context configuration class or the xml configuration file. Set the value of its loader property to WebContextLoader.class.
  3. Add WebApplicationContext field to our test class and annotate it with the @Resource annotation. This field contains a reference to the used web application context.
  4. Add a MockMvc field to our test class. This field contains a reference to the MockMvc object that is used in our integration tests.
  5. Create a public setUp() method and annotate this method with the @Before annotation. This method creates a new MockMvc object by using the static webApplicationContextSetup() method of the MockMvcBuilders class.
Step 6:The source code of our integration test skeleton class looks as follows:

Step7:
It will goes to Controller which is having the path of /grops/database/cluster and it executes that controller and returns the object or string whatever u gave the return type to that method.

Step8:If Assertion is success u will get the following code on console of Junit


Step9:Like this we are testing through MockMvc object.we r getting the output in Json format with the above example.

Step10:This is complete process of JunitTest.

Notes:We can Test Relative Url Rest calls Only
Notes:We can use this from within IDE only for purpose of Unit Test cases and peer reviews only.

Example:

Mycontroller.java
@Controller
@RequestMapping(value = "xyz")
public class MyController {

    @Autowired
    private MyService myService;

    @RequestMapping(value = "/test")
    public String Test( ) {

       System.out.println(“Hello world”);
        return "mvc test";

    }

}

//Writing test cases

MvcTestController.java
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"file:src/main/webapp/WEB-INF/spring/root-context.xml"})
@WebAppConfiguration
public class MvcTestController {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext ctx;
@Before
public void setUp() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(ctx).build();
}
@Test
public void test2() throws Exception {
mockMvc.perform(get("/xyz/test"))
.andDo(print()) //Actual Output
.andExpect(status().isOk())
.andExpect(content().string("abc"));//Expected Outpu
}
}








No comments:

Post a Comment