[英]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.由于速度原因,我想在不需要 Spring 上下文的情况下运行一些单元测试。 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.我只想拥有使用
@Value
的便捷方式,而无需启动整个耗时的上下文。
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
仅加载嵌入的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 {}
}
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 {}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.