SpringBoot JUnit 和@Value

SpringBoot JUnit and @Value

在我的配置中 class 我有

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

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

@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 个位置。我希望它在 vars

中呈现并绑定为列表

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

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