我试图弄清楚如何在使用Eureka的Spring Boot应用程序上构建集成测试。说我有考试

@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返回为空。如果我直接启动Spring Boot应用并自己使用API​​,则代码可以正常工作。我在任何地方都没有特定的个人资料用法。我是否需要配置一些特别的Eureka,以便发现客户端构建用于测试?

最佳答案

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

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

或者如果您使用的是Spring Boot 1.2.1及更高版本
@WebIntegrationTest
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {Application.class})

08-04 16:44