简体   繁体   中英

Using Spring's property injection without having to launch up the whole context

I want to run some unit tests without the need of the Spring context because of speed reasons. But I also like the way I can inject files into my tests

Here is an example testcode I use:

@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);
  }
}

I'd like to have only the convenient way of using @Value without launching the whole time consuming context.

Is this somehow possible?

You could use test empty configuration for such test, it will improve performance. In following example, @SpringBootTest load only embedded EmptyTestContext instead of searching for all 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 {}
}

Also for more readability you could add:

@SpringBootTest(classes = DemoMvcApplicationTest.EmptyTestContext.class)

It has the same effect.

Update , more lightweight variant:

@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 {}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM