使用Eureka服务集成测试Spring Boot服务

Rub*_*sMN 5 java service-discovery spring-boot spring-cloud netflix-eureka

我正在试图弄清楚如何在使用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)));

    }
}
Run Code Online (Sandbox Code Playgroud)

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

DiscoveryManager.getInstance().getDiscoveryClient().getApplications();
Run Code Online (Sandbox Code Playgroud)

这将是NPE.discoveryClient返回null.如果我直接启动Spring启动应用程序并自己使用API​​,代码工作正常.我没有任何具体的配置文件使用.我是否需要为Eureka设置一些特殊的东西,以便为发现客户端进行测试构建?

Rub*_*sMN 6

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

@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {Application.class})
@IntegrationTest
Run Code Online (Sandbox Code Playgroud)

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

@WebIntegrationTest
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {Application.class})
Run Code Online (Sandbox Code Playgroud)

  • 这解决了启动问题,但是您如何在这个伪造的eureka客户端中提供周围系统的URL? (2认同)