全体のコンテキストを起動することなく、Springのプロパティインジェクションを使用して

xetra11:

ため、私はスピードの理由のSpringコンテキストを必要とせずに、いくつかのユニットテストを実行します。しかし、私も、私は私のテストにファイルを挿入することができる方法のように

ここで私は使用例testcodeは次のとおりです。

@ContextConfiguration()
@SpringBootTest
@RunWith(SpringRunner.class)
public class XmlRestructureApplierTest {
  @Value("classpath:export.xml")
  private Resource exportedXML;
  private XmlRestructureApplier applier;


  @Test
  public void shouldRestructureArrayToObjectWithGivenKey() throws IOException, XPathExpressionException, SAXException {
    List<JSONObject> productsAsJSONObjects = XmlElementExtractor.extractToJSON(exportXML.getInputStream(), "PRV");
    assertThat(productsAsJSONObjects).hasSize(6);
  }
}

私が使用しての唯一の便利な方法したいのですが@Value、コンテキストを消費全体の時間を起動せずに。

これは何とか可能ですか?

i.bondarenko:

あなたはそれがパフォーマンスが向上しますが、このようなテストのためのテスト空の構成を使用することができます。次の例では、@SpringBootTest負荷が唯一の組み込みEmptyTestContextすべての検索の代わりにSpringBootConfiguration

@SpringBootTest
@RunWith(SpringRunner.class)
public class DemoMvcApplicationTest {
    @Value("${test.value}")
    private String value;

    @Test
    public void propertyHasValidValue() {
        assertThat(value).isEqualTo("TestValue1");
    }

    @Configuration
    public static class EmptyTestContext {}
}

また、より読みやすくするために、あなたは追加することができます。

@SpringBootTest(classes = DemoMvcApplicationTest.EmptyTestContext.class)

これは、同じ効果があります。

アップデート、より軽量な変種:

@RunWith(SpringRunner.class)
@ContextConfiguration
public class DemoMvcApplicationTest {
    @Value("${test.value}")
    private String value;

    @Test
    public void propertyHasValidValue() {
        assertThat(value).isEqualTo("TestValue1");
    }

    @Configuration
    @PropertySource("classpath:application.properties")
    public static class EmptyTestContext {}
}

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=330219&siteId=1