【问题标题】:Multiple Tests with MockRestServiceServer使用 MockRestServiceServer 进行多项测试
【发布时间】:2020-03-27 21:51:41
【问题描述】:

我的测试在单独执行时运行。当我执行测试类时,其中一个失败了:

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

测试类:

@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();

    }

}

一个测试通过,另一个失败并显示上述错误消息。

感谢您的提示。

【问题讨论】:

    标签: spring-boot spring-boot-test mockrestserviceserver


    【解决方案1】:

    我很抱歉。我在缓存陷阱中运行。第一个测试激活了rest调用的缓存,第二个tets中的第二个rest调用没有被执行。

    测试后我现在清除所有缓存:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-19
      • 2023-03-05
      相关资源
      最近更新 更多