1.Spring Boot中单元测试详解

本文详细介绍了Spring Boot中的单元测试,包括JUnit注解的使用、Spring Boot Test的基本样式和SpringMVC的模拟测试。讨论了如何使用@RunWith、MockMvc和ApplicationContext进行测试,还给出了具体的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一.前言

1.介绍
  • 编写单元测试可以帮助开发人员编写高质量的代码,提升代码质量,减少Bug,便于重构。
  • spring-boot-starter-test也秉承了开箱即用的原则,集成了许多优秀的类库,可以很方便的帮助我们进行测试使用
  • spring-boot测试的核心包,一个为spring-boot-test包含核心项,另一个为spring-boot-test-autoconfigure支持了测试的自动配置
2.集成类库
  • JUnit 4:Java应用程序标注的单元测试

  • Spring Test & Spring Boot Test:对spring boot程序单元测试和集成测试提供支持

  • AssertJ:一个流畅的断言库,提供返回值的测试比较

  • Hamcrest:匹配器对象库(也称为约束或谓词)

  • Mockito:一个Java 模拟框架,用于模拟请求,java bean等

  • JSONassert:对JSON对象或者JSON字符串断言的库

  • JsonPath,提供类似XPath那样的符号来获取JSON数据片段

    可见依赖列表:

3.官方文档
4.项目例子

二.Spring Boot Test

1.基本样式
  • spring boot的测试类,基本接口如下
    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class TestingApplicationTests {
         
         
        @Test
        public void contextLoads() {
         
         
        }
    }
    
    1.@RunWith(SpringRunner.class)@RunWith是一个JUnit4的注解,表明测试运行器,SpringRunner.class表明获取spring上下文支持;如果使用JUnit5可以不用添加此注解,因为@SpringBootTest中集成了@RunWith
    2.@SpringBootTest:加载Web ApplicationContext并提供模拟Web环境,其的搜索算法从包含测试包开始工作,直到找到用@SpringBootApplicationor 或者@SpringBootConfiguration注释的类
2.Junit注解
  • Junit在spring boot test 中大量使用,下面介绍了Junit包含的注解和用法
  • JUnit注解中包含了几个比较重要的注解:@BeforeClass@AfterClass@Before@After@Test@Ignore。其中,@BeforeClass@AfterClass在测试类加载的开始和结束时运行,必须为静态方法;而@Before@After则在每个测试方法开始之前和结束之后运行。@Ignore忽略的测试方法(只在测试类的时候生效,单独执行该测试方法无效),见如下例子:
    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class TestingApplicationTests {
         
         
    
        @Test
        @Ignore
        public void contextLoads() {
         
         
        }
    
        @BeforeClass
        public static void beforeClassTest() {
         
         
            System.out.println("before class test");
        }
    
        @Before
        public void beforeTest() {
         
         
            System.out.println("before test");
        }
    
        @Test
        public void Test1() {
         
         
            System.out.println("test 1*1=1");
            Assert.assertEquals(1, 1 * 1);
        
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值