六、测试模式
1.1.0版本开始增加了apollo-mockserver
,从而可以很好地支持单元测试时需要mock配置的场景,使用方法如下:
6.1 引入pom依赖
<dependency>
<groupId>com.ctrip.framework.apollo</groupId>
<artifactId>apollo-mockserver</artifactId>
<version>1.1.0</version>
</dependency>
6.2 在test的resources下放置mock的数据
文件名格式约定为mockdata-{namespace}.properties
6.3 写测试类
更多使用demo可以参考ApolloMockServerApiTest.java和ApolloMockServerSpringIntegrationTest.java。
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = TestConfiguration.class)
public class SpringIntegrationTest {
// 启动apollo的mockserver
@ClassRule
public static EmbeddedApollo embeddedApollo = new EmbeddedApollo();
@Test
@DirtiesContext // 这个注解很有必要,因为配置注入会弄脏应用上下文
public void testPropertyInject(){
assertEquals("value1", testBean.key1);
assertEquals("value2", testBean.key2);
}
@Test
@DirtiesContext
public void testListenerTriggeredByAdd() throws InterruptedException, ExecutionException, TimeoutException {
String otherNamespace = "othernamespace";
embeddedApollo.addOrModifyPropery(otherNamespace,"someKey","someValue");
ConfigChangeEvent changeEvent = testBean.futureData.get(5000, TimeUnit.MILLISECONDS);
assertEquals(otherNamespace, changeEvent.getNamespace());
assertEquals("someValue", changeEvent.getChange("someKey").getNewValue());
}
@EnableApolloConfig("application")
@Configuration
static class TestConfiguration{
@Bean
public TestBean testBean(){
return new TestBean();
}
}
static class TestBean{
@Value("${key1:default}")
String key1;
@Value("${key2:default}")
String key2;
SettableFuture<ConfigChangeEvent> futureData = SettableFuture.create();
@ApolloConfigChangeListener("othernamespace")
private void onChange(ConfigChangeEvent changeEvent) {
futureData.set(changeEvent);
}
}
}