Junit 5 mockito无法读取Spring Boot应用程序中用@Value注释的属性文件

Des*_*lop 5 java mockito spring-boot junit5 junit-jupiter

我正在为 Spring Boot 应用程序中的一个组件编写 junit 测试用例。该组件具有@Value 注释并从属性文件中读取值。

当我运行 Junit 5 (mockito) 时,控件转到组件;该值为空。

我尝试过的:我使用 @ExtendWith(SpringRunner)并更改@injectMocks@Autowired@mock@MockBeans但这不是我想要的(因为它成为集成测试。)

朱尼特类:

@ExtendWith(MockitoExtension.class)
public class ItemMessageProcessorTest {

    private static final String VALUE1 = "Value 1";
    private static final String VALUE2 = "Value 2";
    private static final String VALUE3 = "Value 3";

    @InjectMocks
    private MyComponent component;

    
Run Code Online (Sandbox Code Playgroud)

组件类:

@Slf4j
@Component
public class MyComponent {

    @Value("${my-val.second-val.final-val}")
    private String myValue;
Run Code Online (Sandbox Code Playgroud)

这个 myValue 正在同一个组件类中使用:

 public void myMethod(){
    myObject.setMyValue(Integer.parseInt(myValue));
}
Run Code Online (Sandbox Code Playgroud)

我正在寻找的是这样的:如果我有机会模拟 parseInt,或者从测试类本身加载值。任何线索都会有很大的帮助。 注意:我无法更改组件类中的任何内容。

Dmi*_*kov 3

您可以只使用 Spring 反射 utills 方法通过 @Value 设置字段值进行单元测试:

org.springframework.test.util.ReflectionTestUtils.setField(classUnderTest, "field", "value");
Run Code Online (Sandbox Code Playgroud)

  • 完美的答案。这就是我刚刚尝试过的并且有效。 (2认同)