SpringBoot入门编写controller层和单元测试

实现CRUD四个接口的ArticleController

@Slf4j
@RestController
@RequestMapping("/rest")
public class ArticleController {

    // 查询一篇文章
   //@RequestMapping(value = "/articles/{id}", method = RequestMethod.GET)
    @GetMapping(value = "/articles/{id}")
    public AjaxResponse getArticle(@PathVariable("id") Long id){
        Article article = Article.builder()
                .id(1L)
                .author("xieyang")
                .content("spring boot 从青铜到王者")
                .createTime(new Date())
                .title("t1").build();

        log.info("article:" + article);
        return AjaxResponse.success(article);
    }

    // 新增一篇文章
    //@RequestMapping(value = "/articles", method = RequestMethod.POST)
    @PostMapping(value = "/articles")
    public AjaxResponse saveArticle(@RequestBody Article article){
        log.info("saveArticle:" + article);
        return AjaxResponse.success(article);
    }

    // 修改一篇文章
    //@RequestMapping(value = "/articles", method = RequestMethod.PUT)
    @PutMapping(value = "/articles")
    public AjaxResponse updateArticle(@RequestBody Article article){
        log.info("updateArticle:" + article);
        return AjaxResponse.success();
    }

    // 删除一篇文章, 根据id
    //@RequestMapping(value = "/articles", method = RequestMethod.DELETE)
    //@DeleteMapping(value = "/articles")
    @DeleteMapping(value = "/articles/{id}")
    public AjaxResponse deleteArticle(@PathVariable("id") Long id){
        log.info("updateArticle:" + id);
        return AjaxResponse.success();
    }
}

编写单元测试

SpringBoot入门编写controller层和单元测试_第1张图片

@Slf4j
public class ArticleRestControllerTest {

    // mock对象
    private static MockMvc mockMvc;

    @BeforeAll
    static void setUp(){
        mockMvc = MockMvcBuilders.standaloneSetup(new ArticleController()).build();
    }

    String article = "{\n" +
            "    \"id\":1,\n" +
            "    \"author\": \"xieyang\",\n" +
            "    \"title\": \"test\",\n" +
            "    \"content\": \"c\",\n" +
            "    \"createTime\": \"2018-09-29 05:23:24\"\n" +
            "}";

    @Test
    public void saveArticle() throws Exception{
        MvcResult mvcResult = mockMvc.perform(
                MockMvcRequestBuilders
                .request(HttpMethod.POST,"/rest/articles")
                .contentType("application/json/")
                .content(article)
        ).andExpect(MockMvcResultMatchers.status().isOk())
         .andExpect(MockMvcResultMatchers.jsonPath("$.data.author").value("xieyang"))
         .andDo(print())
         .andReturn();

        log.info(mvcResult.getResponse().getContentAsString());
    }



}

Mock测试介绍

SpringBoot入门编写controller层和单元测试_第2张图片

SpringBoot入门编写controller层和单元测试_第3张图片

你可能感兴趣的:(算法)