Spring Boot中如何通过JUnit为@Value注解字段设置测试值
问题解决思路
首先你的代码存在一个核心语法错误:@Value注解的参数必须用双引号包裹,正确写法应为@Value("${name.firstname:'F NAME'}")。未加引号会导致Spring无法解析属性表达式,这是字段始终为null的直接原因。
以下是几种在JUnit测试中为firstname和lastname赋值的可行方案:
方案1:基于Spring上下文的集成测试(推荐)
如果测试需要依赖Spring容器(比如用到其他组件),可以借助Spring测试框架实现:
方式1:测试类内直接指定属性值
使用@TestPropertySource硬编码属性:
@SpringBootTest @TestPropertySource(properties = { "name.firstname=Test_First", "name.lastname=Test_Last" }) class ATest { @Autowired private A a; @Test void testTargetMethod() { a.iWantedToBeTested(); // 输出Test_First和Test_Last } }
方式2:通过application-test.yml配置
在src/test/resources目录下创建application-test.yml:
name: firstname: YML_First lastname: YML_Last
然后在测试类激活test环境:
@SpringBootTest @ActiveProfiles("test") class ATest { @Autowired private A a; @Test void testTargetMethod() { a.iWantedToBeTested(); // 输出YML_First和YML_Last } }
方案2:不加载Spring上下文的单元测试
如果仅需单独测试A类,无需启动Spring容器,可以用Spring的ReflectionTestUtils直接设置私有字段:
import org.springframework.test.util.ReflectionTestUtils; import org.junit.jupiter.api.Test; class ATest { @Test void testTargetMethod() { A a = new A("sample_a_value"); // 对应@RequiredArgsConstructor的构造参数 ReflectionTestUtils.setField(a, "firstname", "Reflect_First"); ReflectionTestUtils.setField(a, "lastname", "Reflect_Last"); a.iWantedToBeTested(); // 输出Reflect_First和Reflect_Last } }
内容的提问来源于stack exchange,提问作者Aayush Sahu
相关产品推荐
相关产品推荐

