TDD-使用mockmvc来测试接口

2019-12-26  本文已影响0人  写代码的杰西

之前写springboot,测试接口使用的都是postman。先写代码再测试。
在知道tdd的概念以后,尝试用tdd的方法去写一个接口。


需求:展示文章分页列表
入参:分页dto(json)
出参:文章list


参考链接:https://www.jianshu.com/p/91045b0415f0

先写test类,写好测试类以后再去一点点补充代码。
不太想码字了,贴代码吧。用法在参考链接里

import cn.jesseyang.blog.entity.dto.PageDto;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import org.junit.Before;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
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.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;

@SpringBootTest
@AutoConfigureMockMvc
public class ArticleTests {
    @Autowired
    private MockMvc mockMvc;
    @Autowired
    protected WebApplicationContext wac;
    @Before()  //这个方法在每个方法执行之前都会执行一遍
    public void setup() {
        mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();  //初始化MockMvc对象
    }
    @Test
    public void articlePageTest(){
        try {
            PageDto pageDto = new PageDto();
            pageDto.setCurrent(1);
            pageDto.setSize(10);
            ObjectMapper mapper = new ObjectMapper();
            ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();
            java.lang.String requestJson = ow.writeValueAsString(pageDto);
            mockMvc.perform(get("/article/list-by-page")
            .contentType(MediaType.APPLICATION_JSON)
            .content(requestJson))
            .andDo(print())
            .andExpect(MockMvcResultMatchers.jsonPath("$.total").value(1))
            .andReturn().getResponse().getContentAsString();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public void testMvc(){
        try {
            mockMvc.perform(get("/article/list")
                    .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                    .param("aa","bb"))
                    .andDo(print())
                    .andReturn().getResponse().getContentAsString();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

controller

    @RequestMapping("list-by-page")
    @ResponseBody
    public IPage<Article> listByPage(@RequestBody PageDto pageDto){
        return articleService.getArticleByPage(pageDto);
    }
上一篇下一篇

猜你喜欢

热点阅读