一、问题背景:想要把配置文件中的配置在测试的时候加载到测试类中,但是执行下来,发现@Value在测试方法执行时,不生效。参数总是加载为null 。

springboot 版本:2.6.4

二、原因排查
(一)查找@Value 生效前提如下:
1、不能作用于 static final 修饰的属性;
2、不能作用于非注册类,即用@Component 及其衍生注解的类;
3、类的使用只能通过依赖注入的方式,不能用new的方式;

以上三点,只有第三点我不满足,于是我在测试类中添加了被测试类的依赖注入@Autowired,测试发现注入的实例hiveDeal一直为null。

(二)解决测试类依赖注入实例失败问题
查找资料可知:Spring 中,实例由容器管理,测试类中,容器因为没有对应的上下文,没有办法进行注入类的实例化操作,因此需要提供一个上下文环境给我测试类,即添加如下两个注解到测试类。

@RunWith(SpringRunner.class) //意指让程序运行于Spring测试环境
@SpringBootTest(classes = HiveDeal.class) //给测试类提供上下文环境

注解说明
@RunWith 类级别注解,提供了一种更改测试运行程序的默认机制。可以根据指定的类运行程序,指定的类必须是Runner类的子类。
@SpringBootTest 通过这个注解,可以使JUnit单元测试执行在SpringBoot 环境中,提供上下文环境。

最终程序如下:

//测试类节选
import org.junit.jupiter.api.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;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = HiveDeal.class)
class HiveDealTest {

    @Autowired
    private HiveDeal hiveDeal;

    @Test
    public void executeDDLTest(){
        //hiveDeal = new HiveDeal();
        hiveDeal.execute("create table autotest_tb(name string) partitioned by(ds string)");
    }
}
//被测试类节选
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class HiveDeal {
    @Value("${jdbc.hive.driver}")
    private String hiveDriver;

    @Value("${jdbc.hive.url}")
    private String hiveUrl;
}

参考资料:
springboot @Value无效原因:https://blog.csdn.net/ITzhongzi/article/details/105489035
java报错空指针异常_分析使用Spring Boot进行单元测试时,报出空指针异常:https://blog.csdn.net/weixin_33146151/article/details/112368289

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐