六、测试模式

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)
  2. @SpringApplicationConfiguration(classes = TestConfiguration.class)
  3. public class SpringIntegrationTest {
  4. // 启动apollo的mockserver
  5. @ClassRule
  6. public static EmbeddedApollo embeddedApollo = new EmbeddedApollo();
  7. @Test
  8. @DirtiesContext // 这个注解很有必要,因为配置注入会弄脏应用上下文
  9. public void testPropertyInject(){
  10. assertEquals("value1", testBean.key1);
  11. assertEquals("value2", testBean.key2);
  12. }
  13. @Test
  14. @DirtiesContext
  15. public void testListenerTriggeredByAdd() throws InterruptedException, ExecutionException, TimeoutException {
  16. String otherNamespace = "othernamespace";
  17. embeddedApollo.addOrModifyPropery(otherNamespace,"someKey","someValue");
  18. ConfigChangeEvent changeEvent = testBean.futureData.get(5000, TimeUnit.MILLISECONDS);
  19. assertEquals(otherNamespace, changeEvent.getNamespace());
  20. assertEquals("someValue", changeEvent.getChange("someKey").getNewValue());
  21. }
  22. @EnableApolloConfig("application")
  23. @Configuration
  24. static class TestConfiguration{
  25. @Bean
  26. public TestBean testBean(){
  27. return new TestBean();
  28. }
  29. }
  30. static class TestBean{
  31. @Value("${key1:default}")
  32. String key1;
  33. @Value("${key2:default}")
  34. String key2;
  35. SettableFuture<ConfigChangeEvent> futureData = SettableFuture.create();
  36. @ApolloConfigChangeListener("othernamespace")
  37. private void onChange(ConfigChangeEvent changeEvent) {
  38. futureData.set(changeEvent);
  39. }
  40. }
  41. }