Spring Boot:(2)单元测试

引入单元测试依赖

  • 在 pom.xml 文件中引入spring boot 单元测试依赖
        <!--单元测试依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>

创建单元测试类

  • 在需要创建单元测试的类名上按 Ctrl+Shift+t,会弹出一个"Create New Test…"
    在这里插入图片描述
  • 点击"Create New Test…" 在弹出的窗口中选择需要进行单元测试的方法,然后点击OK
    在这里插入图片描述
  • src/test/java路径下,自动生成测试类"HelloWorldControllerTest"
    在这里插入图片描述
  • 除了以上自动生成测试类方法,也可以在src/test/java路径下,手动创建类,用于测试。

编写测试类内容

  • 在生成的测试类的顶部添加注解
@RunWith(SpringRunner.class)
@SpringBootTest
  • Controller单元测试,使用 MockMvc 实现对Http请求的模拟。
package org.mur.controller;

import org.junit.jupiter.api.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 static org.hamcrest.CoreMatchers.equalTo;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc// 配置 MockMvc
class HelloWorldControllerTest {
    @Autowired
    private MockMvc mvc;

    @Test
    void index() throws Exception{
        mvc.perform(MockMvcRequestBuilders.get("/hello")
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(content().string(equalTo("Hello World!")));
    }
}
  • 执行测试方法。鼠标放在对应的方法,右键选择run该方法即可。
    在这里插入图片描述
  • 测试结果,测试通过。
    在这里插入图片描述

异常处理

  • 1
  • 告警内容:
  • Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=…) with your test
  • 解决方法:
  • 在注解上加上 @SpringBootTest(classes = Application.class)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值