【问题标题】:@Value coming as null in junit 5@Value 在junit 5中为空
【发布时间】:2021-12-14 15:04:03
【问题描述】:

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

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

控制器类

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

}

【问题讨论】:

    标签: java spring spring-boot junit junit5


    【解决方案1】:

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

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

    【讨论】:

    • controller 是控制器类的对象名吧?它给了我错误必填字段提供了 ControllerClass
    • param 1 controller 是您要修改的对象。参数 2 items 是您要放置数据的字段的名称。 Param 3 items 是您要放置在该字段上的值。
    【解决方案2】:

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

    @PropertySource("classpath:values.properties")
    class ControllerClass {
    
    @Value("${app.items}")
    String[] items; -- coming as null while running test cases
    
    // remaing code 
    
    }
    

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

    【讨论】:

      猜你喜欢
      • 2019-03-25
      • 1970-01-01
      • 1970-01-01
      • 2022-08-19
      • 2022-06-21
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 2020-01-05
      相关资源
      最近更新 更多