java - @TestPropertySource - 测试属性文件中的值未设置/设置为 null

标签 java spring junit null properties-file

我的 Junit 没有获取测试属性文件中设置的属性。 我没有收到错误,但从属性文件返回的值为空

要测试的类别:

package com.abc.mysource.mypackage;

@Component
@ComponentScan
public class MyHelper {

    @Autowired
    @Qualifier("commonProperties")
    private CommonProperties commonProperties;  

    public LocalDateTime method1ThatUsesCommonProperties(LocalDateTime startDateTime) throws Exception {
        String customUserType = commonProperties.getUserType(); // Returns null if run as JUnit test
        //Further processing
    }
}

支持组件 - Bean 和配置类:

package com.abc.mysource.mypackage;
@Component
public class CommonProperties {
     @Value("${myhelper.userType}")
     private String userType;

         public String getUserType() {
        return userType;
    }
    public void setCalendarType(String userType) {
        this.userType = userType;
    }
}

配置类:

package com.abc.mysource.mypackage;
@Configuration
@ComponentScan(basePackages ="com.abc.mysource.mypackage.*")
@PropertySource("classpath:default.properties")
public class CommonConfig {}

src/main/resources下的default.properties

myhelper.userType=PRIORITY

我的测试课:

package com.abc.mysource.mypackage.test;
@RunWith(SpringRunner.class)
@ContextConfiguration(classes=MyHelper.class)
@TestPropertySource("classpath:default-test.properties")
@EnableConfigurationProperties
public class MyHelperTest {
    @MockBean(name="commonProperties")
    private CommonProperties commonProperties;

    @Autowired
    private MyHelper myHelper;

    @Test
    public void testMethod1ThatUsesCommonProperties() {
        myHelper.method1ThatUsesCommonProperties();
    }
}

default-test.properties 定义在/src/test/resources 下:

myhelper.userType=COMMON

注意:

我将 default-test.properties 移至/src/main/resources - commonProperties.getUserType() 为 null

我什至使用了@TestPropertySource(properties = {"myhelper.userType=COMMON"})。结果相同

注2:

我尝试了 @TestPropertySource is not loading properties 上的解决方案.

此解决方案要求我在 src/test/java 下创建一个名为 CommonProperties 的重复 bean。但是当我这样做时 @MockBean 失败了

@MockBean(name="commonProperties")
private CommonProperties commonProperties;

请不要标记重复项。

注3: 我的是一个spring,而不是一个spring boot应用程序。

最佳答案

如果您不需要特定状态,MockBeans 就适合。通常这个bean是“隔离的”,并且这个bean的每个方法调用都会有相同的结果。它是“隔离的”->使用@Value注释的服务将不适用于此bean。

您需要的是一个正确构造和初始化的“正常”bean。请使用 @Autowired 注释并根据需要使用测试配置文件定义另一个 bean。

关于java - @TestPropertySource - 测试属性文件中的值未设置/设置为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52858552/

相关文章:

java - 我认为我在编译Java文件时遇到问题

java - 操作数应包含 1 列插入

java - RabbitMQ、docker、单队列、多个消费者

java - 验证是否调用了所有 getter 方法

java - Neo4j 在 IntelliJ IDEA 的 JUnit 测试中运行时登录服务器扩展

java - 用户 'root' @'localhost' 的访问被拒绝

java - 如何编写该程序以包含字符串的最后一个字母?

java - 如何在 application.yml Spring Cloud Gateway 中指定自定义过滤器

java - Spring Boot 1.5.10 间歇性 RestRepositoryController 404 问题?

unit-testing - 许多测试类还是一个测试类具有多种方法?