Michael Hegner
Michael Hegner

Reputation: 5823

Multiple Tests with MockRestServiceServer

My Tests run through when executing them separatly. When I execute the Test Class, then one of them fails:

java.lang.AssertionError: Further request(s) expected leaving 1 unsatisfied expectation(s).
0 request(s) executed.

Test-Class:

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("test")
@Transactional
public class ProductListControllerIT {

    @Autowired RestTemplate restTemplate;
    @Autowired MockMvc      mvc;

    @Test
    public void testGet_1() throws Exception {
        MockRestServiceServer mockServer = MockRestServiceServer.createServer(restTemplate);
        mockServer.expect(ExpectedCount.once(),
            requestTo(/* any url */))
            .andExpect(method(HttpMethod.GET))
            .andRespond(withStatus(HttpStatus.OK)
                    .contentType(MediaType.APPLICATION_JSON)
                    .body(/* JSON-STRING */)
            );

        var model = mvc.perform(MockMvcRequestBuilders.get("/url")
            .andReturn().getModelAndView().getModel();

        mockServer.verify();

    }

    @Test
    public void testGet_2() throws Exception {
        MockRestServiceServer mockServer = MockRestServiceServer.createServer(restTemplate);
        mockServer.expect(ExpectedCount.once(),
            requestTo(/* any url */))
            .andExpect(method(HttpMethod.GET))
            .andRespond(withStatus(HttpStatus.OK)
                    .contentType(MediaType.APPLICATION_JSON)
                    .body(/* JSON-STRING */)
            );

        var model = mvc.perform(MockMvcRequestBuilders.get("/url")
            .andReturn().getModelAndView().getModel();

        mockServer.verify();

    }

}

One test pass, the other fails with error message as described above.

Thanks for hints.

Upvotes: 0

Views: 1255

Answers (1)

Michael Hegner
Michael Hegner

Reputation: 5823

I apologize. I run in a cache pitfall. The first test activated the cache for the rest call, the second rest call in the second tets has not been executed.

I clear all caches now after tests:

@After
public void after() {
    mockServer.verify();
    cacheManager.getCacheNames().forEach(n -> cacheManager.getCache(n).clear());
}

Upvotes: 2

Related Questions