You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用@TestPropertySource无法初始化布尔属性的问题排查

问题原因及解决办法

你的问题核心在于没有让Spring容器管理Calculator实例,导致@TestPropertySource和@Value注解完全未生效:

  1. 你在@Before方法里手动new Calculator(),这个对象并非Spring容器创建,Spring不会处理它的@Value注解,因此isEnabled字段只是Java boolean类型的默认值false,和你配置的calculator.enabled=true毫无关联。
  2. 测试断言Assert.assertFalse(calculator.isEnabled())刚好和默认值匹配,才会出现"本应失败的测试意外通过"的情况。

修正后的测试代码

@RunWith(SpringRunner.class)
@SpringBootTest // 加载Spring上下文,也可以用@ContextConfiguration(classes = Calculator.class)
@TestPropertySource(properties = {"calculator.enabled=true"})
public class CalculatorTest {

    @Autowired // 注入Spring容器管理的Calculator实例
    private Calculator calculator;

    @Test
    public void isEnabled_Success_Test() {
        Assert.assertTrue(calculator.isEnabled()); // 断言需改为true,匹配配置值
    }
}

关键修改说明

  • 移除手动new Calculator()的代码,改用@Autowired注入Spring容器创建的实例,这样Spring才会处理@Value注解,读取@TestPropertySource设置的属性值。
  • 通过@SpringBootTest或@ContextConfiguration让测试类加载Spring上下文,确保Calculator被识别为Bean并由容器管理。
  • 修正测试断言:因配置了calculator.enabled=true,需断言isEnabled()返回true,才能验证配置是否生效。

内容的提问来源于stack exchange,提问作者Shubham Gupta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 09:00:51