0

I'm testing the new servlet 3 asynchronous requests in my new project and get stuck while testing the controller.

I have a controller method like this:

@RequestMapping(value = "/thumbnails", method = RequestMethod.GET)
public Callable<ResponseEntity<List<Thumbnail>>> getAllThumbnails() {
    //at this point I get results from the repository
    return () -> {
        //at this point I don't get any results
        final List<Thumbnail> thumbnails = thumbnailRepository.findAll();
        return ResponseEntity.ok(thumbnails);
    };
}

And a corresponding test like this:

@Test
@Transactional
public void testGetAllThumbnails() throws Exception {
    thumbnailRepository.saveAndFlush(thumbnail);

    final MvcResult mvcResult = restThumbnailMockMvc.perform(get("/test/thumbnails"))
                                                    .andExpect(request().asyncStarted())
                                                    .andExpect(request().asyncResult(instanceOf(ResponseEntity.class)))
                                                    .andReturn();

    mvcResult.getAsyncResult();

    restThumbnailMockMvc.perform(asyncDispatch(mvcResult))
                        .andDo(print())
                        .andExpect(status().isOk())
                        .andExpect(content().contentType(MediaType.APPLICATION_JSON))
                        .andExpect(jsonPath("$.[*].id").value(hasItem(thumbnail.getId().longValue())))
                        .andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME)))
                        .andExpect(jsonPath("$.[*].fileName").value(hasItem(DEFAULT_FILE_NAME)));
}

The Repository and stuff is a simple spring data jpa bean and the whole configuration is based on spring boot.

If I query the controller in a normal way every thing works fine but in the test the repository returns no results.

Many thanks for your help on that in advanced, I can not find anything similar on the web.

conscience
  • 463
  • 6
  • 21

1 Answers1

0

Ok after a bit trial and error I figured out what went wrong.

The Problem is/was that the test method run in a transaction and for some reason the same transaction could not be accessed in the callable of the controller while the test runs. After removing the @Transactional annotation from the test method every thing works fine.

conscience
  • 463
  • 6
  • 21