解决SpringBoot 测试类无法自动注入@Autowired的问题

    首先,在springboot中要使用测试类 就要在maven中导入相关依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

     然后就可以在springboot中使用测试类来进行使用

package www.com.baidu.test;

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 www.com.baidu.pojo.Cars;
import www.com.baidu.service.CarsService;
import www.com.baidu.week03;

import java.util.List;

/**
 * @Auther: chenyulong
 * @Date: 2024/1/25 10:25
 * @Description:
 */

@RunWith(SpringRunner.class)
@SpringBootTest(classes = week03.class)
public class MyTest {
    @Autowired
    CarsService carsService;
    @Test
    public void test1(){
        List<Cars> carsList = carsService.findCarsList(new Cars());
        for (Cars cars : carsList) {
            System.out.println(cars);
        }
    }
}

这里面关键的就是类上面的两个注解:

      @RunWith(SpringRunner.class) 是一个 JUnit 注解,它告诉 JUnit 使用 SpringRunner 来运行测试。SpringRunner 是 Spring TestContext Framework 的一部分,它提供了整合 Spring 和 JUnit 的功能。

  @SpringBootTest(classes = week03.class) 是一个 Spring Boot 注解,用于指定 Spring Boot 应用程序的入口类。它表示当前测试是一个集成测试,会加载完整的 Spring ApplicationContext。

   其中 classes 参数用于指定 Spring Boot 应用程序的主配置类。在这个例子中,week03.class 应该是你的主配置类的名称。通过指定主配置类,Spring Boot 在启动测试时会加载该类及其相关的配置文件,创建应用程序的上下文环境。

   综上所述,使用这两个注解可以实现在测试环境中加载完整的 Spring ApplicationContext,并使用 SpringRunner 来运行测试。

  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值