mercredi 24 février 2016

Testing Spring boot REST resource issues

There is a microservice made with Spring Boot. It consist of Jetty, Jersey, Jackson and Liquibase. One of tasks of this service is to receive some data via REST and return response. This operation goes through next units: - MyResource.java, @Component REST with JAX-RS annotations, that receives data and ask @Autowired MyService for response. - MyService.java, @Component service with @Autowired MyResource to ask it for response. - MyResource.java, simple @JpaRepository interface

This application works fine, but now I need to add some tests for every module. Usually I use Mockito to test units, so I test my service with mocked MyRepository (Mockito @Mock annotation + when() method). I want to test MyResource.java the same way.

I tried to use TestRestTemplate way to test with spring-boot-starter-test and my test class looks like this:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebIntegrationTest(randomPort = true)
public class MyResourceTest {
  @Value("${local.server.port}")
  private int port;

  private String getBaseUrl() {
    return "http://localhost:" + port;
  }

  @Test
  public void test() {
    final TestRestTemplate restTemplate = new TestRestTemplate();
    assertEquals(restTemplate.postForEntity(getBaseUrl() + "/test", null, ResponseObject.class).getBody(), new ResponseObject());
  }
}

And there are two problems. First - when my test is running, they run up whole spring application, so my liquibase scripts is trying to find database and this is a very long-time process. Second - I can't replace MyService class with Mockito proxy.

I tried to find some manuals about best practices in testing spring boot REST applications and I found MockMvc-based way, but it looks like don't run up server to run test. Can you please share your way to test REST resource in spring boot?

Aucun commentaire:

Enregistrer un commentaire