【问题标题】:SpringBoot JUnit and @ValueSpring Boot JUnit 和 @Value
【发布时间】:2023-04-02 12:44:01
【问题描述】:

在我的配置类中我有

@Value("${some.vars}")
private List<String> vars;

现在在我的测试中,我希望能够设置 this 的值,所以我有这个

@SpringBootTest
public class MyTest {

 @Test
 public void test() {
   ApplicationContextRunner runner = new ApplicationContextRunner();
   runner
   .withConfiguration(AutoConfigurations.of(MyConfiguration.class))
   .withUserConfiguration(UserConfiguration.class)
   .withPropertyValues("some.vars=A,B,C")
   .run(ctx -> {
     // some test assertions
   }); 
 }

我将A,B,C 作为一个字符串绑定到List&lt;String&gt; 的第0 个位置。我希望它在vars 中呈现并绑定为 List

【问题讨论】:

    标签: java spring spring-boot junit4


    【解决方案1】:

    你需要额外的工作来将字符串拆分为列表

    @Value("#{'${some.vars}'.split(',')}") 
    private List<String> vars;
    

    【讨论】:

    • 太棒了!!如何在此处也将默认值设置为 #{null}?
    • 我检查过,但我不知道这种组合如何与拆分调用和默认值一起使用。
    • null 是什么意思? List vars 是 null 吗?或者你 wnat List vars 是空的?
    • 检查一次{some.vars:A,B,C,D,E,F}它应该有,而不是.句点@user3833308
    • 我认为@user3833308 想要 "A.B.C","D.E.F" 作为两个字符串
    猜你喜欢
    • 1970-01-01
    • 2019-03-25
    • 1970-01-01
    • 2020-11-18
    • 2016-07-16
    • 2016-12-27
    • 2019-03-24
    • 2021-07-18
    • 1970-01-01
    相关资源
    最近更新 更多