springboot的MockMvc单元测试(测试controller层方法)

所谓单元测试,即用一小段可以独立运行的代码,去测试一个比较底层的单独的功能。

如果需要对controller层的方法进行测试,那么我们可以使用springboot提供的MockMvc,模拟客户端的请求来测试。

 一、引入依赖

   只有我们去执行测试类时,该依赖才会被加载  

<!--集成单元测试junit需要的依赖 --> 
<dependency> 
	<groupId>org.springframework.boot</groupId> 
	<artifactId>spring-boot-starter-test</artifactId> 
	<scope>test</scope> 
</dependency>

二、理论知识详解

1.@RunWith

该注解为类级别批注,该注解的作用是告诉java这个类是以什么运行环境来运行

2.@SpringBootTest

  启动spring容器,用来指定springboot应用程序的入口类,该注解会根据包名逐级向上查找,一直找到一个springboot的主程序为止,然后启动该类为单元测试准备spring上下文环境,参数是启动类的字节码文件

三、创建测试类

 在test目录下创建测试类

//参数是启动类的字节码文件
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringbootApplication.class)
public class TestEmp {
    @Autowired
    private EmpMapper empMapper;

  //测试方法要求无参无返回值无静态
    @Test
    public void testGetEmpByEname(){
        List<Emp> emps = empMapper.getEmpByEname("乔");
        for (Emp emp:emps) {
            System.out.println(emp);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/YMYYZ/article/details/128575990