如何正确创建一个SpringBoot的测试类

文章讲述了在SpringBoot项目中,除了基本的web依赖外,还需要引入测试相关的依赖如spring-boot-test、junit和spring-test。创建测试类时,需使用@SpringBootTest和@RunWith(SpringRunner.class)注解,特别是后者,它是实现Bean注入的关键。示例展示了如何编写一个测试用例,通过UserMapper查询用户列表。

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

  1. 需要正确导入依赖,除了springboot必需的web等依赖以外,还需要导入测试依赖

            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-test</artifactId>
            </dependency>
        
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-test</artifactId>
                <version>5.2.1.RELEASE</version>
            </dependency>
    
  2. 创建一个测试类,需要加上@SpringBootTest注解和@RunWith(SpringRunner.class)注解,其中后者十分重要,如果没有此注解就无法去注入bean对象。

    package com.zcy;
    
    import com.zcy.domain.User;
    import com.zcy.mapper.UserMapper;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.test.context.junit4.SpringRunner;
    import java.util.List;
    
    @SpringBootTest
    @RunWith(SpringRunner.class)
    public class MybatisTest {
    
        @Autowired
        private UserMapper userMapper;
    
        @Test
        public void xTest() throws Exception {
            List<User> user = userMapper.selectList(null);
            System.out.println(user);
        }
    
    }
    
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值