使用@RunWith(SpringRunner.class)进行Junit测试(单元测试中使用@Autowired或者@Resource注入资源)

本文介绍了如何在JUnit测试中解决@Autowired注解导致的NullPointerExecption问题。首先,需要引入Spring的测试相关依赖,包括SpringRunner和@SpringBootTest。然后,在测试类上使用@RunWith(SpringRunner.class)和@SpringBootTest注解,使测试类能够利用Spring容器。通过这种方式,可以成功注入并使用如RedisTemplate等资源进行测试。示例代码展示了如何注入RedisTemplate并在测试方法中使用。

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

在使用Junit进行单元测试的时候有可能会需要使用@Autowired或者@Resource进行注入或者装配,但是单纯的使用Junit进行这些操作时会报NullPointerExecption,因为这样无法使用spring容器中的资源,我们知道@Autowired和@Resource装配注入的资源都在spring容器中,那怎么才能成功装配注入进来呢?

第一步:配置需要使用的依赖包:

        <!--spring的测试包:SpringRunner和@RunWith在这个包中-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <scope>compile</scope>
        </dependency>
        <!--spring的测试包:@SpringBootTest在这个包中-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-test</artifactId>
        </dependency>
        <!--@Test在这个包中-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>

第二步:使用spring容器中的资源

代码:

import org.apache.log4j.Logger;
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.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringTestDemo {

    private final Logger logger = Logger.getLogger(SpringTestDemo.class);
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Test
    public void set(){
        logger.info("已经连接上redis开始写入数据!");
        redisTemplate.opsForValue().set("myKey","myValue");
        System.out.println(redisTemplate.opsForValue().get("myKey"));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值