5

I'm trying to figure out how to build integration tests on a Spring Boot application that uses Eureka. Say I have a test

@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)));

    }
}

and I have in my code path for that api call:

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

This will NPE. The discoveryClient is returned as null. Code works fine if I start the Spring boot app directly and use the API myself. I have no specific profile usage anywhere. Is there something special wrt Eureka that I need to configure for the discovery client to get constructed for testing?

RubesMN
  • 939
  • 1
  • 12
  • 22
  • 2
    Is there a reason you can't/don't want to run your test with `@IntegrationTest` like [here](https://github.com/spring-cloud-samples/eureka/blob/master/src/test/java/eurekademo/ApplicationTests.java)? – Donovan Muller May 21 '15 at 05:37
  • Yup.. you are right. I could use `@IntegrationTest` or `@WebIntegrationTest`. Cant keep up with all these new annotations! Solves the problem perfectly. I will answer and modify the code for others. – RubesMN May 21 '15 at 14:58

1 Answers1

6

Thanks to @Donovan who answered in the comments. There are annotations built by Phillip Web and Dave Syer in the org.springframework.boot.test package that I was unaware of. Wanted to provide an answer with the changed code. Change the class annotations to:

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

or if you are using spring boot 1.2.1 and greater

@WebIntegrationTest
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {Application.class})
RubesMN
  • 939
  • 1
  • 12
  • 22