SpringBoot 测试及 MockMvc的使用

2021-03-03 11:48:16 浏览数 (1)

1. @SpringBootTest 单元测试


1. 添加依赖
代码语言:javascript复制
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-test</artifactId>
	<scope>test</scope>
</dependency>
2. 添加测试类
代码语言:javascript复制
package com.test.spring_boot_demo;

import junit.framework.TestCase;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class) // 底层用junit  SpringJUnit4ClassRunner
@SpringBootTest(classes = {SdSpringBootApplication.class}) // 启动整个SpringBoot工具
public class SpringBootDemoTest {

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

    @Test
    public void testTwo() {
        System.out.println("test hello 2");
        TestCase.assertEquals(1, 1);
    }

    @Before
    public void testBefore() {
        System.out.println("before");
    }

    @After
    public void testAfter() {
        System.out.println("after");
    }

}
3. 运行测试
  • 如果测试某个方法,直接运行要测试的方法。
  • 如果测试类中的多个方法,直接运行测试类。

2. MocMvc(模拟MVC请求,实现接口测试)


1. 添加测试接口(Controller)
代码语言:javascript复制
@GetMapping("/test/home")
public String testHome() {
    return "test home ...";
}
2. 添加测试类
代码语言:javascript复制
package com.test.spring_boot_demo;

import org.junit.Test;
import org.junit.runner.RunWith;
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.test.context.junit4.SpringRunner;
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.MockMvcResultMatchers;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {SdSpringBootApplication.class})
@AutoConfigureMockMvc
public class MockMvcDemoTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void apiTest() throws Exception {
        // perform: 执行一个 RequestBuilder 请求
        // andExpect: 添加 ResultMatcher -> MockMvcResultMatchers 验证规则
        // andReturn: 最后返回相应的 MvcResult
        MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/test/home")).
                andExpect(MockMvcResultMatchers.status().isOk()).andReturn();
        int status = mvcResult.getResponse().getStatus();
        System.out.println(status);
    }

}

0 人点赞