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);
        }
    }
}

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Spring Boot中,可以使用JUnit和MockMvc来进行Controller单元测试。下面是一个示例: ```java import org.junit.Before; 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.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc public class MyControllerTest { @Autowired private MockMvc mockMvc; @Before public void setup() { // 在每个测试方法执行前的初始化操作 } @Test public void testController() throws Exception { mockMvc.perform(MockMvcRequestBuilders.get("/api/mycontroller") .contentType(MediaType.APPLICATION_JSON)) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.jsonPath("$.name").value("John")) .andExpect(MockMvcResultMatchers.jsonPath("$.age").value(25)); } } ``` 上述代码中,我们使用了`@RunWith(SpringRunner.class)`注解来指定使用SpringRunner运行测试。`@SpringBootTest`注解用于加载Spring Boot应用程序上下文。`@AutoConfigureMockMvc`注解用于自动配置MockMvc实例。 在`testController`方法中,我们使用`MockMvc`执行了一个GET请求,并验证了返回的状态码和JSON响应的内容。 需要注意的是,上述示例中的路径`/api/mycontroller`和JSON响应的内容`name`和`age`是根据具体的Controller和返回值来设置的,你需要根据你的实际情况进行修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值