Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integration Testing Spring Boot service using Eureka services

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?

like image 208
RubesMN Avatar asked May 21 '15 00:05

RubesMN


1 Answers

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})
like image 149
RubesMN Avatar answered Oct 27 '22 00:10

RubesMN