欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

单元测试MockMvc用法

时间:2023-06-15

package com.heima.article.controller.v1;

import com.heima.model.article.dtos.ArticleInfoDto;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
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.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

@SuppressWarnings(“all”)
@SpringBootTest
@RunWith(SpringRunner.class)
//使用MocMvc进行测试 SpringBoot提供的
@AutoConfigureMockMvc
public class ArticleInfoControllerTest {
@Autowired
MockMvc mvc;
@Autowired
ObjectMapper mapper;

@Testpublic void testLoadArticleInfo() throws Exception { ArticleInfoDto dto = new ArticleInfoDto(); dto.setArticleId(10120);//1为数据库中的测试数据 MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.post("/api/v1/article/load_article_info") .contentType(MediaType.APPLICATION_JSON_VALUE) .content(mapper.writevalueAsBytes(dto));//String.valueOf(dto)与此用mapper的方法有啥不同 mvc.perform(builder).andExpect(MockMvcResultMatchers.status().isOk()).andDo(MockMvcResultHandlers.print());}

}
f

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。