SpringBoot对Controller进行单元测试的实现代码 附乱码解决方案
短信预约 -IT技能 免费直播动态提醒
Controller代码
package com.keafmd.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@RestController
public class HelloController {
@RequestMapping("/hello")
Map hello(){
Map map = new HashMap();
map.put("keafmd","牛哄哄的柯南");
map.put("success",true);
return map;
}
}
单元测试代码
package com.keafmd;
import com.keafmd.SpringBoot02Application;
import com.keafmd.controller.HelloController;
import org.junit.jupiter.api.BeforeEach;
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.context.ContextConfiguration;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
@SpringBootTest(classes = SpringBoot02Application.class)
@AutoConfigureMockMvc //相当于是使用 context 上下文构造一个 mvc对象
public class MvcTest {
//模拟访问 Controller
@Autowired
MockMvc mvc;
@Test
public void test() throws Exception {
MvcResult result = mvc.perform(
MockMvcRequestBuilders.get("/hello").
accept(MediaType.APPLICATION_JSON)).
andExpect(MockMvcResultMatchers.status().isOk()).
andDo(MockMvcResultHandlers.print()).andReturn();
}
}
测试结果
乱码解决
把注解替换为:↓
@RequestMapping(value = "/hello",produces = {"application/json;charset=UTF-8"})
HelloController:
package com.keafmd.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@RestController
public class HelloController {
@RequestMapping(value = "/hello",produces = {"application/json;charset=UTF-8"})
//@RequestMapping("/hello")
Map hello(){
Map map = new HashMap();
map.put("keafmd","牛哄哄的柯南");
map.put("success",true);
return map;
}
}
解决乱码后的效果:
到此这篇关于SpringBoot对Controller进行单元测试的实现代码 附乱码解决方案的文章就介绍到这了,更多相关SpringBoot Controller单元测试内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341