zoukankan      html  css  js  c++  java
  • SpringBoot项目单元测试

    前一段时间,有朋友问到springboot运用如何进行单元测试,结合LZ公司的实际运用,这里给大家描述一下三种单元测试的方式。

    1.约定

    单元测试代码写在src/test/java目录下
    单元测试类命名为*Test,前缀为要测试的类名

    2. 使用mock方式单元测试

    Spring测试框架提供MockMvc对象,可以在不需要客户端-服务端请求的情况下进行MVC测试,完全在服务端这边就可以执行Controller的请求,跟启动了测试服务器一样。
    测试开始之前需要建立测试环境,setup方法被@Before修饰。通过MockMvcBuilders工具,使用WebApplicationContext对象作为参数,创建一个MockMvc对象。

    @RunWith(SpringRunner.class)
    @SpringBootTest(classes = Application.class)//这里的Application是springboot的启动类名
    @WebAppConfiguration
    public class StyleControllerTest {
    
        @Autowired
        private WebApplicationContext context;
    
        private MockMvc mockMvc;
    
        private ObjectMapper mapper = new ObjectMapper();
    
        @Before
        public void setupMockMvc() throws Exception {
            mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
        }
    
        @Test
        public void testSend() throws Exception {
            Long id =1l;
            //调用接口,传入添加的用户参数
            mockMvc.perform(MockMvcRequestBuilders.get("/style/listStyleById")
                    .contentType(MediaType.APPLICATION_JSON_UTF8)
                    .content(mapper.writeValueAsString(id)))
                    .andExpect(MockMvcResultMatchers.status().isOk())
                    .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON_UTF8))
                    .andDo(MockMvcResultHandlers.print());
    
        }
    
    }
    
    

    3. 使用Feign方式单元测试

    以下是Feign接口的单元测试示例,启动项目,可以测试本jar提供的服务,不启动服务,改为远程服务地址,可以测试远程jar提供的服务
    其中

    @EnableFeignClients(clients = UserControllerTest.UserServiceFeignClient.class)
    
    

    类似我们实际应用调用相关服务一样。

    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringBootTest(classes = UserControllerTest.class)
    @Import({ FeignAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class })
    @EnableFeignClients(clients = UserControllerTest.UserServiceFeignClient.class)
    public class UserControllerTest {
    
        @FeignClient(value = "loan-server", url = "http://localhost:9070/")
        public interface UserServiceFeignClient extends UserServiceClient {
        }
    
        @Autowired
        private UserServiceFeignClient userServiceFeignClient;
    
        @Test
        public void getUser() {
            User user = userServiceFeignClient.getSDKUserById(1);
            System.out.println(user);
        }
    }
    
    

    4. 使用Http Rest API 单元测试

    使用RestTemplate发起GET或POST请求,其中@SpringBootTest这两行注释掉就不启动SpringBoot容器直接进行远程调用测试

    @RunWith(SpringJUnit4ClassRunner.class)
    public class LoanControllerTest {
    
        private  final  static String url =  "http://localhost:9070/";
    
        private static RestTemplate restTemplate = new RestTemplate();
    
        @Test
        public void test(){
            ResponseEntity<String> response = restTemplate.exchange(url + "/loan/getLoanById?id=1" ,
                    HttpMethod.GET,
                    new HttpEntity(null),
                    String.class);
            System.out.println("result: " + response.getBody());
        }
    }
    
    
    

    欢迎大家扫码关注我的微信公众号,与大家一起分享技术与成长中的故事。
    我的微信公众号.jpg

  • 相关阅读:
    千万别用树套树 【题意:有多少线段完全覆盖某一线段【树状数组维护】】【模板题】
    Codeforces Round #590 (Div. 3)【D题:26棵树状数组维护字符出现次数】
    Codeforces Round #590 (Div. 3)【D题:维护26棵树状数组【好题】】
    Codeforces Round #350 (Div. 2) A B C D1 D2 水题【D2 【二分+枚举】好题】
    AtCoder Beginner Contest 142【D题】【判断素数的模板+求一个数的因子的模板】
    AtCoder Beginner Contest 116 D
    序列自动机【模板】
    题解 CF1428G Lucky Numbers (Easy Version and Hard Version)
    题解 CF1428F Fruit Sequences
    题解 P5401 [CTS2019]珍珠
  • 原文地址:https://www.cnblogs.com/shunyang/p/8681111.html
Copyright © 2011-2022 走看看