我想测试依赖于使用@Autowired和@ConfigurationProperties加载的属性的应用程序的一小部分.我正在寻找一个只加载所需属性的解决方案,而不是整个ApplicationContext.这里以简化为例:
@TestPropertySource(locations = "/SettingsTest.properties")
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {TestSettings.class, TestConfiguration.class})
public class SettingsTest {
@Autowired
TestConfiguration config;
@Test
public void testConfig(){
Assert.assertEquals("TEST_PROPERTY", config.settings().getProperty());
}
}
Run Code Online (Sandbox Code Playgroud)
配置类:
public class TestConfiguration {
@Bean
@ConfigurationProperties(prefix = "test")
public TestSettings settings (){
return new TestSettings();
}
}
Run Code Online (Sandbox Code Playgroud)
设置类:
public class TestSettings {
private String property;
public String getProperty() {
return property;
}
public void setProperty(String property) {
this.property = property;
}
}
Run Code Online (Sandbox Code Playgroud)
资源文件夹中的属性文件包含以下条目:
test.property=TEST_PROPERTY
Run Code Online (Sandbox Code Playgroud)
在我当前的设置配置不是null,但没有可用的字段.字段不是字段的原因应该与我不使用Springboot但是Spring的事实有关.那么Springboot的运行方式是什么呢?
编辑: 我想这样做的原因是:我有一个解析Textfiles的解析器,使用的正则表达式存储在属性文件中.为了测试这个,我想只加载这个解析器所需的属性,它们位于TestSettings之上的exaple中.
在阅读评论时,我已经注意到这不再是单元测试了.但是,对于这个小测试使用完整的Spring启动配置对我来说似乎有点太多了.这就是为什么我问是否有可能只加载一个属性的类.
我目前正在使用 Camel 的模拟组件,我想在现有的路线上测试它。基本上我想保留应用程序中定义的现有路由,但在测试期间注入一些模拟,以验证或至少查看当前的交换内容。
基于文档和 Apache Camel Cookbook。我尝试过使用@MockEndpoints
这是路线构建器
@Component
public class MockedRouteStub extends RouteBuilder {
private static final Logger LOGGER = LoggerFactory.getLogger(MockedRouteStub.class);
@Override
public void configure() throws Exception {
from("direct:stub")
.choice()
.when().simple("${body} contains 'Camel'")
.setHeader("verified").constant(true)
.to("direct:foo")
.otherwise()
.to("direct:bar")
.end();
from("direct:foo")
.process(e -> LOGGER.info("foo {}", e.getIn().getBody()));
from("direct:bar")
.process(e -> LOGGER.info("bar {}", e.getIn().getBody()));
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的测试(目前是一个 springboot 项目):
@RunWith(SpringRunner.class)
@SpringBootTest
@MockEndpoints
public class MockedRouteStubTest {
@Autowired
private ProducerTemplate producerTemplate;
@EndpointInject(uri = "mock:direct:foo")
private MockEndpoint mockCamel;
@Test
public void test() throws InterruptedException { …Run Code Online (Sandbox Code Playgroud)