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

Viewed 68

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?

1 Answers

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