java - @Value 在 junit 5 中为 null

标签 java spring spring-boot junit junit5

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

您能告诉我如何实现这一目标吗?

Controller 类

class ControllerClass {

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

// remaing code 

}

application-test.yml

app:
 items: a, b, c, d

测试类

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

关于java - @Value 在 junit 5 中为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69770556/

相关文章:

java - Android 中的 ListActivities 如何与 ListView 配合使用?

java - 谷歌应用引擎和 mongodb

java - Vaadin Crud 用户界面。轴排序不正确

java - 由于未声明异常,编译失败,即使已声明

java - 如何使用运行时参数创建原型(prototype)范围的 @Bean?使用 getBean(String name, Object...args)?

Spring Boot :Injection of autowired dependencies failed;

带有 quartz 调度程序的 spring 4

java - 带有 AcceptHeaderLocaleResolver 和 i18n 的 Spring Security

spring-boot - SpringBoot Keycloak NoSuchMethodError : javax. ws.rs.core.UriBuilder.resolveTemplates

java - Spring Boot 1.3 使用模拟嵌套 Bean 进行测试