@Value 在 junit 5 中为 null

@Value coming as null in junit 5

我正在测试我的应用程序,但在 运行 测试用例时我收到 NUllPointer 异常,因为它无法映射 YML 文件中的值。

你能告诉我如何实现吗?

控制器类

class ControllerClass {

@Value("${app.items}")
String[] items; -- coming as null while running test cases

// remaing code 

}

申请-test.yml

app:
 items: a, b, c, d

测试class

@SpringJUnitConfig
@SpringBootTest
@ActiveProfiles("test)
class TestControllerClass {

@InjectMock
ControllerClass controller;

@Mock
ServiceClass service;

@Test
//test case

}

Mockito 不知道该怎么做 - 你可以手动完成:

 @Before
    public void setUp() {
        String[] items = new String[2];
        items[0] = "a";
        items[1] = "b";
        ReflectionTestUtils.setField(controller, "items", 
               items);
    }

自然地,我们需要一个属性文件来定义我们想要使用@Value 注释注入的值。因此,我们首先需要在我们的配置中定义一个@PropertySource class — 使用属性文件名。

@PropertySource("classpath:values.properties")
class ControllerClass {

@Value("${app.items}")
String[] items; -- coming as null while running test cases

// remaing code 

}

如果它不起作用,请使用 。 properties 文件如提到的 here.