【问题标题】:@TestPropertySource - Values not set / set as null from test properties file@TestPropertySource - 值未从测试属性文件设置/设置为空
【发布时间】:2019-03-22 08:23:43
【问题描述】:

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

要测试的类:

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() 为空

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

注意 2:

我在@TestPropertySource is not loading properties上尝试了解决方案。

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

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

请不要标记重复。

注意 3: 我的是一个弹簧,而不是一个弹簧启动应用程序。

【问题讨论】:

  • 你的问题对我有帮助,谢谢。

标签: java spring junit null properties-file


【解决方案1】:

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

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

【讨论】:

  • Changing MockBean -> Autowired 修复了这个问题。
猜你喜欢
  • 2011-09-03
  • 2023-03-31
  • 2022-01-23
  • 2011-10-14
  • 1970-01-01
  • 1970-01-01
  • 2023-03-28
  • 2018-02-18
  • 1970-01-01
相关资源
最近更新 更多