集成测试 Spring 使用 Eureka 服务启动服务

Integration Testing Spring Boot service using Eureka services

我正在尝试弄清楚如何在使用 Eureka 的 Spring 引导应用程序上构建集成测试。假设我有一个测试

@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {Application.class})
public class MyIntegrationTest {
  @Autowired
  protected WebApplicationContext webAppContext;

  protected MockMvc mockMvc;
  @Autowired
  RestTemplate restTemplate;

  @Before
  public void setup() {
    this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build();
  }

  @Test
  public void testServicesEdgeCases() throws Exception {

    // test no registered services
    this.mockMvc.perform(get("/api/v1/services").accept(MediaType.APPLICATION_JSON).contentType(MediaType.APPLICATION_JSON))
        .andDo(print())
        .andExpect(status().isOk())
        .andExpect(jsonPath("$").value(jsonArrayWithSize(0)));

    }
}

我的代码路径中有那个 api 调用:

DiscoveryManager.getInstance().getDiscoveryClient().getApplications();

这将是 NPE。 discoveryClient 返回为 null。如果我直接启动 Spring 启动应用程序并自己使用 API,代码工作正常。我在任何地方都没有特定的配置文件使用情况。我需要为发现客户端配置一些特殊的 wrt Eureka 来构建测试吗?

感谢@Donovan 在评论中的回答。 org.springframework.boot.test 包中有 Phillip Web 和 Dave Syer 构建的注释,我不知道。想用更改后的代码提供答案。将 class 注释更改为:

@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {Application.class})
@IntegrationTest

或者如果您使用的是 spring boot 1.2.1 及更高版本

@WebIntegrationTest
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {Application.class})