首页 > 解决方案 > SpringBoot JUnit 和 @Value

问题描述

在我的配置类中,我有

@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<String>它的第 0 个位置。我希望它能够呈现并绑定为 List invars

标签: javaspringspring-bootjunit4

解决方案


您需要额外的工作才能将字符串拆分为列表

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

推荐阅读