Junit 5 mockito无法读取spring引导应用程序中带有@Value注释的属性文件 &g



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

当我运行我的Junit 5(模拟)和控件去组件;值为空

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

Junit类:

@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;

组件类:

@Slf4j
@Component
public class MyComponent {
@Value("${my-val.second-val.final-val}")
private String myValue;

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

public void myMethod(){
myObject.setMyValue(Integer.parseInt(myValue));
}

我要找的东西是这样的:如果我可以模拟parseInt,或者从测试类本身加载值。任何线索都会很有帮助。

您可以使用Spring reflection utills方法为单元测试设置字段值@Value:

org.springframework.test.util.ReflectionTestUtils.setField(classUnderTest, "field", "value");

在这种情况下我将使用构造函数注入:

@Slf4j
@Component
public class MyComponent {
private final String myValue;
MyComponent(@Value("${my-val.second-val.final-val}" String myValue)) {
this.myValue = myValue;
}
}

application.properties中的值被加载到Spring Application Context在这些情况下:

  • 当应用程序正在运行时,
  • Spring Integration测试
  • runnign。

在单元测试属性未加载的情况下。

如果你有一个构造函数注入您可以为测试设置一个值,并将其传递给构造函数。

最重要的是,您不希望加载整个Spring Application上下文来自动绑定属性,因为这会极大地减慢单元测试的执行速度。因此,你不能使用@ExtendWith(SpringRunner)。

你可以使用reflectiontesttils和@ExtendWith(MockitoExtension.class)来绑定MyComponent类的属性。

org.springframework.test.util.ReflectionTestUtils.setField(MyComponent.class, "myValue", 1);