junit 如何在Spring中同一个单元测试类的不同方法中声明不同的属性

ss2ws0br  于 12个月前  发布在  Spring
关注(0)|答案(1)|浏览(109)

我希望有一个单元测试类来测试类@ConfigurationProperties("...") MyConfig的初始化,给定不同的配置属性集。
举例来说:

@SpringBootTest(classes = { MyConfig.class })
@DirtiesContext // to force re-initialization of context
class MyConfigTest {
  @Autowired
  MyConfig myConfig;

  @Test
  @UseProperties("my-config.prop1=foo") // Looking for something like this?
  void test1() {
    assertThat(myConfig).doesSomething(...);
  }

  @Test
  @UseProperties("my-config.prop1=bar")
  void test2() {
    assertThat(myConfig).doesSomethingElse(...);
  }

  @Test
  @UseProperties("my-config.prop1=foobar")
  void test3() {
    assertThat(myConfig).doesSomethingTotallyDifferent(...);
  }
}

(显然,我完全编造了@UseProperties注解,它只是为了解释我在寻找什么)。

93ze6v8z

93ze6v8z1#

我在这个GitHub repo中找到了解决方案
test可以使用ObjectMapperMap的不同属性集。

final Yaml yaml = new Yaml();
final Object map = yaml.load(resource.getInputStream());
final ObjectWriter ow = new ObjectMapper().writer();
final String myConfigAsString = ow.writeValueAsString(map);
final MyConfig myConfig = new ObjectMapper()
                .readValue(myConfigAsString, MyConfig.class);

一个缺点是ObjectMapper不能识别Configuration类的前缀(因为它不是作为bean加载的),所以您必须使用空字符串,或者不填写值并从yaml中删除缩进。

相关问题