springboot之单元测试

1.引入相关依赖:

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

2、在项目工程的test目录下生成测试类,或者使用idea新建工程时生成测试类,写一个简单测试方法,测试程序能否启动。

@RunWith(SpringRunner.class)
@SpringBootTest
//@SpringBootTest(classes={MybatisApplication.class})
public class MybatisApplicationTests {

    @Test
    public void test1(){
        System.out.println("test1");
        TestCase.assertEquals(1,1);
    }
}

3、注入MockMvc客户端对象,使用如下2种方式之一,否则会抛MockMvc空指针。
3.1 在application-test.yml配置文件中设置

  spring:
    datasource:
      druid:
        web-stat-filter:
            enabled: false

3.2 添加@AutoConfigureMockMvc注解,引入mockmvc对象。并在测试类上添加@ActiveProfiles(“test”)

 @Autowired
 private MockMvc mockMvc;

或者使用如下方式注入MockMvc对象。
// public MockMvc mockMvc;
//
// @Autowired
// private WebApplicationContext webApplicationContext;
//
// @Before
// public void setUp() throws Exception {
// mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
// }

4.测试:
4.1 Get Api接口测试

无参数的get请求:
   @Test
    public void getApiTest() throws Exception {
        MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/test/get/msg")
                                          ).andReturn();
        int status = result.getResponse().getStatus();
        System.out.println(status);
        String content = result.getResponse().getContentAsString();
        System.out.println("content="+content);


有参数的get请求:
   @Test
    public void getApiTest() throws Exception {
        MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/test/get/msg")
                                                                 .param("name","xxx")
                                          ).andReturn();
        int status = result.getResponse().getStatus();
        System.out.println(status);

        String content = result.getResponse().getContentAsString();
        System.out.println("content="+content);


    }

4.2 Post Api接口测试

    @Test
    public void postApiTest() throws Exception{
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("test1","1");
        httpHeaders.add("test2","2");
  
        HashMap<String, String> map = new HashMap<>();
        map.put("name","xixi");
        map.put("age","20");
        String param = JSON.toJSONString(map);

        MvcResult result = mockMvc.perform(MockMvcRequestBuilders.post("/test/post")
                                                                 .contentType(MediaType.APPLICATION_JSON_UTF8)
                                                               //.param("name","xixi") //用于测试 @RequestParam注解的入参
                                                               //.param("age","20")
                                                                .content(param) //用于测试 @RequestBody注解的入参
                                                               //.content("{\"age\":\"18\",\"name\":\"haha\"}")	
                                                               //.headers(httpHeaders)
                                           )
//                                           .andExpect(status().isOk())
                                            .andReturn();//返回

        System.out.println(result.getResponse().getStatus());
        String content=result.getResponse().getContentAsString();//返回体
        System.out.println("content="+content);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot的单元测试是开发过程中不可或缺的一部分,它允许开发者对应用程序的各个模块进行独立的测试,确保每个组件的功能正确无误。在Spring Boot中,测试主要依赖于Spring Test框架,特别是JUnit和Mockito等工具。 以下是Spring Boot单元测试的一些关键概念和步骤: 1. **测试类**:通常创建一个继承自`SpringBootTest`或其子类的测试类,如`@RunWith(SpringRunner.class)`注解用于使用Spring的测试运行器。 ```java import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest public class MyServiceTest { // 测试代码... } ``` 2. **@Autowired注解**:Spring会自动注入被测试对象(通常是`@Component`或`@Service`)到测试类中,便于进行依赖注入的测试。 ```java @Autowired private MyService myService; ``` 3. **@MockBean或@SpyBean**:Spring Test提供了`Mockito`库的支持,可以模拟(mock)或部分地模拟对象的行为,便于测试特定的方法。 4. **@Test方法**:定义测试用例,调用被测试对象的方法并验证结果。例如,使用`assertThat`检查预期输出。 ```java @Test public void testMyMethod() { // 预期结果 List<String> expected = Arrays.asList("foo", "bar"); // 调用方法 List<String> result = myService.myMethod(); // 验证结果 assertThat(result, is(equalTo(expected))); } ``` 5. **@Transactional**:如果你的测试涉及到数据库操作,可以使用`@.Transactional`来保证测试环境的一致性,事务会在测试开始前开启并在测试结束后回滚。 6. **@SpringBootTest(classes = MyClass.class)**:如果你想测试整个Spring应用上下文,可以指定要加载的类或配置。 相关问题: 1. Spring Boot的单元测试和集成测试有什么区别? 2. 如何在Spring Boot中编写数据库相关的单元测试? 3. `@SpringBootTest`和`@WebMvcTest`的区别是什么?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值