当前位置:   article > 正文

SpringBoot之单元测试_springboot junit不测试filter

springboot junit不测试filter

MockMvc实现了对Http请求的模拟,能够直接使用网络的形式,转换到Controller的调用,这样可以使得测试速度快、不依赖网络环境,而且提供了一套验证的工具,这样可以使得请求的验证统一而且很方便。

controller

  1. @RestController
  2. public class IndexController {
  3. @RequestMapping("/index")
  4. public String index() {
  5. return "index";
  6. }
  7. }

测试controller

  1. package com.xxx.demo.controller;
  2. import org.junit.Before;
  3. import org.junit.Test;
  4. import org.junit.runner.RunWith;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
  7. import org.springframework.boot.test.context.SpringBootTest;
  8. import org.springframework.http.MediaType;
  9. import org.springframework.test.context.ContextConfiguration;
  10. import org.springframework.test.context.junit4.SpringRunner;
  11. import org.springframework.test.web.servlet.MockMvc;
  12. import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
  13. import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
  14. import org.springframework.test.web.servlet.setup.MockMvcBuilders;
  15. import com.abc.demo.controller.IndexController;
  16. @RunWith(SpringRunner.class)
  17. @SpringBootTest(classes=IndexController.class)
  18. @AutoConfigureMockMvc
  19. public class IndexControllerTest {
  20. @Autowired
  21. private MockMvc mockMvc;
  22. //初始化操作
  23. @Before
  24. public void setUp(){
  25. mockMvc=MockMvcBuilders.standaloneSetup(new IndexController()).build();
  26. }
  27. @Test
  28. public void index() throws Exception{
  29. mockMvc.perform(MockMvcRequestBuilders.get("/index")
  30. .accept(MediaType.APPLICATION_JSON))
  31. .andExpect(MockMvcResultMatchers.status().isOk());
  32. }
  33. }
推荐文章: https://blog.csdn.net/vqhgWJl9EUB/article/details/78930280
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/653866
推荐阅读
相关标签
  

闽ICP备14008679号