Spring Boot Rest controller unit tests

Spring Boot provides an easy way to write unit tests for the Rest Controller file. With the help of SpringJUnit4ClassRunner and MockMvc, you can create a Web application context to write unit tests for Rest Controller file.
Unit tests should be written in src/test/javathe directory for writing the test classpath resources should be placed in src/test/resourcesthe directory.
For the preparation of unit tests, we need to add Spring Boot Starter Test dependencies, as shown in the construction of the configuration file.

<dependency>
   <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> 
XML

Gradle users can build.gradle add the following file dependencies.

testCompile('org.springframework.boot:spring-boot-starter-test')

Before writing test cases, you should first build RESTful Web services. For more information on building RESTful Web services, see the same chapter of this tutorial given.

REST controller to write unit tests

In this section, we take a look at how to write unit tests for REST controller.
First, we need to create a class file used to create Abstract Web application context by using MockMvc, and the definition mapToJson()and mapFromJson()method to convert Java objects to JSON string and JSON string into Java objects.

package com.yiibai.demo;

import java.io.IOException; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; 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; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = DemoApplication.class) @WebAppConfiguration public abstract class AbstractTest { protected MockMvc mvc; @Autowired WebApplicationContext webApplicationContext; protected void setUp() { mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); } protected String mapToJson(Object obj) throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); return objectMapper.writeValueAsString(obj); } protected <T> T mapFromJson(String json, Class<T> clazz) throws JsonParseException, JsonMappingException, IOException { ObjectMapper objectMapper = new ObjectMapper(); return objectMapper.readValue(json, clazz); } } 
Java

Next, write an extended AbstractTestclass file, and for each method (such as GET, POST, PUTand DELETE) write unit tests.

We are given below GET API test code. This API is used to view the list of products.

@Test
public void getProductsList() throws Exception { String uri = "/products"; MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.get(uri) .accept(MediaType.APPLICATION_JSON_VALUE)).andReturn(); int status = mvcResult.getResponse().getStatus(); assertEquals(200, status); String content = mvcResult.getResponse().getContentAsString(); Product[] productlist = super.mapFromJson(content, Product[].class); assertTrue(productlist.length > 0); } 
Java

POST API test code is as follows. This API is used to create the product.

@Test
public void createProduct() throws Exception { String uri = "/products"; Product product = new Product(); product.setId("3"); product.setName("Ginger"); String inputJson = super.mapToJson(product); MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.post(uri) .contentType(MediaType.APPLICATION_JSON_VALUE).content(inputJson)).andReturn(); int status = mvcResult.getResponse().getStatus(); assertEquals(201, status); String content = mvcResult.getResponse().getContentAsString(); assertEquals(content, "Product is created successfully"); } 
Java

We are given below PUT API test code. This API is used to update existing products.

@Test
public void updateProduct() throws Exception { String uri = "/products/2"; Product product = new Product(); product.setName("Lemon"); String inputJson = super.mapToJson(product); MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.put(uri) .contentType(MediaType.APPLICATION_JSON_VALUE).content(inputJson)).andReturn(); int status = mvcResult.getResponse().getStatus(); assertEquals(200, status); String content = mvcResult.getResponse().getContentAsString(); assertEquals(content, "Product is updated successsfully"); } 
Java

Delete API test code is as follows. This API will delete the existing product.

@Test
public void deleteProduct() throws Exception { String uri = "/products/2"; MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.delete(uri)).andReturn(); int status = mvcResult.getResponse().getStatus(); assertEquals(200, status); String content = mvcResult.getResponse().getContentAsString(); assertEquals(content, "Product is deleted successsfully"); } 
Java

Complete test controller class file code is as follows -

package com.yiibai.demo;

import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import com.yiibai.demo.model.Product; public class ProductServiceControllerTest extends AbstractTest { @Override @Before public void setUp() { super.setUp(); } @Test public void getProductsList() throws Exception { String uri = "/products"; MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.get(uri) .accept(MediaType.APPLICATION_JSON_VALUE)).andReturn(); int status = mvcResult.getResponse().getStatus(); assertEquals(200, status); String content = mvcResult.getResponse().getContentAsString(); Product[] productlist = super.mapFromJson(content, Product[].class); assertTrue(productlist.length > 0); } @Test public void createProduct() throws Exception { String uri = "/products"; Product product = new Product(); product.setId("3"); product.setName("Ginger"); String inputJson = super.mapToJson(product); MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.post(uri) .contentType(MediaType.APPLICATION_JSON_VALUE) .content(inputJson)).andReturn(); int status = mvcResult.getResponse().getStatus(); assertEquals(201, status); String content = mvcResult.getResponse().getContentAsString(); assertEquals(content, "Product is created successfully"); } @Test public void updateProduct() throws Exception { String uri = "/products/2"; Product product = new Product(); product.setName("Lemon"); String inputJson = super.mapToJson(product); MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.put(uri) .contentType(MediaType.APPLICATION_JSON_VALUE) .content(inputJson)).andReturn(); int status = mvcResult.getResponse().getStatus(); assertEquals(200, status); String content = mvcResult.getResponse().getContentAsString(); assertEquals(content, "Product is updated successsfully"); } @Test public void deleteProduct() throws Exception { String uri = "/products/2"; MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.delete(uri)).andReturn(); int status = mvcResult.getResponse().getStatus(); assertEquals(200, status); String content = mvcResult.getResponse().getContentAsString(); assertEquals(content, "Product is deleted successsfully"); } } 
Java

Create an executable JAR file and use Gradle or Maven command shown below to run Spring Boot application -

For Maven, the commands below -

mvn clean install
Shell

Now, you see the test results in the console window.

Guess you like

Origin www.cnblogs.com/borter/p/12423886.html