@SpringBootTest 为@Service 类编写测试用例,但@Value 未填充

问题描述 投票:0回答:1

我正在使用 Spring boot 3.0.3,并且正在为 Service 类编写测试用例。 我正在使用 @SpringBootTest 和 Junit5。

测试正在运行,但问题是我从属性文件中注入了@Value,但是一旦我运行测试,它就是空的。有趣的是,如果我在测试类本身中注入相同的属性,它就可以正常工作。

@Service
Class Service{
@Value(some.value) private String someValue; // It is null when test is running
}

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
class ServiceTest {
@Value(some.value) private String someValue; // It is working here
@InjectMocks
private Service service; // Service has some mocks 
}

知道出了什么问题吗?

我希望 @Value 在运行测试用例时应按预期在服务中工作。

更新:如果我使用 @Autowired 而不是 @InjectMcks 它可以工作,但我也必须注入一个模拟。

spring spring-boot unit-testing integration-testing
1个回答
0
投票

您需要提供具有定义值的 application-test.yml 文件 或者你可以利用 ReflectionTestUtils 来实现同样的目的

例如你的情况 这会起作用

@BeforeEach
public void setup(){
ReflectionTestUtils.setField(service, “someValue”, “set value here”);
}
© www.soinside.com 2019 - 2024. All rights reserved.