As mentioned in the previous article (Spring Boot Web API), it is very convenient to provide a Web API in the Spring Boot project. As a developer, I have to test my API first before passing it to others. Apis are made to be called, so communication and testing are especially important.

Programmer testing, of course, unit testing. Below is a complete unit test code. The API to be tested is the POST access API, and there are two: one submission parameter format is JSON, and the other is key-value pair.

import api.entity.Author;
import api.entity.EnumSex;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;

@RunWith(SpringRunner.class)
@SpringBootTest
public class MyTest {
    @Autowired
    private WebApplicationContext wac;

    private MockMvc mockMvc;
    
    @Before
    public void setUp(a) {
        mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
    }

    @After
    public void after(a) throws Exception {
        mockMvc = null;
    }

    @Test
    public void testJson(a) throws Exception {// Test submission parameters are in JSON format
        Author req = new Author();//Author is a custom class
        req.setName("zhang3");
        req.setDesc("foolish");
        req.setSex(EnumSex.Male);
        
        ObjectMapper mapper = new ObjectMapper();
        ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();
        java.lang.String requestJson = ow.writeValueAsString(req);
        
        mockMvc.perform(MockMvcRequestBuilders.post("/api/authors/json/1? t=108")
                .contentType(MediaType.APPLICATION_JSON).content(requestJson))
                .andDo(print())
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andReturn().getResponse().getContentAsString();

        System.out.println("ok!!!");
    }

    @Test
    public void testKv(a) throws Exception {// Test submission parameters in key-value pair format
        Author req = new Author();
        req.setName("li4");
        req.setDesc("foolish");
        req.setSex(EnumSex.Male);
        
        ObjectMapper mapper = new ObjectMapper();
        ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();
        java.lang.String requestJson = ow.writeValueAsString(req);
        
        mockMvc.perform(MockMvcRequestBuilders.post("/api/authors/kv/1? t=108")
                .contentType(MediaType.APPLICATION_FORM_URLENCODED).content(requestJson))
                .andDo(print())
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andReturn().getResponse().getContentAsString();

        System.out.println("ok!!!"); }}Copy the code

Attach the API:

@RestController
@RequestMapping(value="/api")
public class ApiController {

	// The submitted argument is JSON
	// The main thing is the @requestBody annotation
    @RequestMapping(value = "/authors/json/{id}", method = RequestMethod.POST)
    public String test(@PathVariable int id, @RequestParam("t") int type,@RequestBody Author auth){
        return String.format("id:%1$d,type:%2$d,name:%3$s; params type:json",id,type,auth.getName());
    }

	// The submitted arguments are key-value pairs
    @RequestMapping(value = "/authors/kv/{id}", method = RequestMethod.POST)
    public String test2(@PathVariable int id, @RequestParam("t") int type,Author auth){
        return String.format("id:%1$d,type:%2$d,name:%3$s; params type:key-value",id,type,auth.getName()); }}Copy the code

Note that unit test classes and methods should be public.

To run a unit test, right-click the method and run.