mardi 16 janvier 2018

Test JSON from paginated request with Rest Template instead of MockMvc

I have written a test for a paginated request. I've used MockMvc since it allows to easily test JSON. The test works correctly. However @AutoConfigureMockMvc annotation on the test class launches spring context for the second time after @SpringBootTest annotation(which is used in its super class that extends AbstractTestNGSpringContextTests). So it's trying to use the same port and as a result fails to load ApplicationContext.

I wonder how this may be solved? Is it possible to change the test so it works with Rest Template?

@Test
    @Transactional
    public void getPage() throws Exception {
        Long total = 5L;
        Pageable pageRequest = new PageRequest(0, 2);

        Page<Product> products = new RestResponsePage<>(createProducts(), pageRequest, total);

        when(productRepository.findAll(any(Pageable.class))).thenReturn(products);

        mockMvc.perform(get("/product/?page=0&size=2"))
                .andExpect(jsonPath("$.totalElements", Matchers.is(5)))
                .andExpect(jsonPath("$.totalPages", Matchers.is(3)));

        verify(productRepository, times(1)).findAll(pageRequest);

    }

Aucun commentaire:

Enregistrer un commentaire