六、测试模式

1.1.0版本开始增加了apollo-mockserver,从而可以很好地支持单元测试时需要mock配置的场景,使用方法如下:

6.1 引入pom依赖

  1. <dependency>
  2. <groupId>com.ctrip.framework.apollo</groupId>
  3. <artifactId>apollo-mockserver</artifactId>
  4. <version>1.1.0</version>
  5. </dependency>

6.2 在test的resources下放置mock的数据

文件名格式约定为mockdata-{namespace}.properties

image

6.3 写测试类

更多使用demo可以参考ApolloMockServerApiTest.javaApolloMockServerSpringIntegrationTest.java

  1. @RunWith(SpringJUnit4ClassRunner.class)@SpringApplicationConfiguration(classes = TestConfiguration.class)public class SpringIntegrationTest { // 启动apollo的mockserver @ClassRule public static EmbeddedApollo embeddedApollo = new EmbeddedApollo();

  2. @Test @DirtiesContext // 这个注解很有必要,因为配置注入会弄脏应用上下文 public void testPropertyInject(){ assertEquals("value1", testBean.key1); assertEquals("value2", testBean.key2); }

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

  4. @EnableApolloConfig("application") @Configuration static class TestConfiguration{ @Bean public TestBean testBean(){ return new TestBean(); } }

  5. static class TestBean{ @Value("${key1:default}") String key1; @Value("${key2:default}") String key2;

  6. SettableFuture&lt;ConfigChangeEvent&gt; futureData = SettableFuture.create();
  7. @ApolloConfigChangeListener(&#34;othernamespace&#34;)
  8. private void onChange(ConfigChangeEvent changeEvent) {
  9.   futureData.set(changeEvent);
  10. }
  11. }}