Spring Boot2使用MockMvc测试API接口

一、引入maven依赖。

<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

二、写API接口。

@RestController
public class HelloController {

	@GetMapping("/hello")
	public String hello(String name) {
		System.out.println("当前时间:" + LocalDateTime.now());
		return "Hello World!我是" + name + ",哈哈哈!";
	}
	
	@PostMapping("/test")
	public String test(String name, String age) throws JsonProcessingException {
		return "name:" + name + ",age:" + age;
	}
	
}

三、写测试代码(注意:测试类的命名应该是需要测试的类名+"Test",测试方法的命名应该是"test"+需要测试的方法名)。

@RunWith(SpringRunner.class)
@SpringBootTest
public class HelloControllerTest {

	@Autowired
    private WebApplicationContext context;
	
    private MockMvc mvc;

    @Before
    public void setUp() throws Exception {
        // 构造MockMvc
        mvc = MockMvcBuilders.webAppContextSetup(context).build();

    }
    
    @Test
    public void testHello() throws Exception {
        mvc.perform(
                 get("/hello")
                .param("name", "zhh"))// 参数
                .andExpect(status().isOk())// 判断接收到的状态是否是200(静态导入)
                .andDo(print());// 打印请求和响应的详情
    }
    
    @Test
    public void testTest() throws Exception {
    	MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
    	map.add("name", "zhh");
    	map.add("age", "24");
    	
    	String result = mvc.perform(post("/test")
							.params(map))// 参数
						.andExpect(MockMvcResultMatchers.status().isOk())
						.andReturn().getResponse().getContentAsString();
    	System.out.println(result);
    }
    
}

四、执行Junit测试,查看结果。

当前时间:2018-07-22T17:19:51.832

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /hello
       Parameters = {name=[zhh]}
          Headers = {}
             Body = <no character encoding set>
    Session Attrs = {}

Handler:
             Type = com.zhh.demo.controller.HelloController
           Method = public java.lang.String com.zhh.demo.controller.HelloController.hello(java.lang.String)

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = {Content-Type=[text/plain;charset=UTF-8], Content-Length=[38]}
     Content type = text/plain;charset=UTF-8
             Body = Hello World!我是zhh,哈哈哈!
    Forwarded URL = null
   Redirected URL = null
          Cookies = []
2018-07-22 17:19:51.868  INFO 12112 --- [           main] o.s.b.t.m.w.SpringBootMockServletContext : Initializing Spring FrameworkServlet ''
2018-07-22 17:19:51.869  INFO 12112 --- [           main] o.s.t.web.servlet.TestDispatcherServlet  : FrameworkServlet '': initialization started
2018-07-22 17:19:51.871  INFO 12112 --- [           main] o.s.t.web.servlet.TestDispatcherServlet  : FrameworkServlet '': initialization completed in 2 ms
name:zhh,age:24

五、其它高级特性:比如事务回滚等,本文不做测试。

注意:更详细的教程请参考https://blog.csdn.net/u012160319/article/details/80507089

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值