You need to enable JavaScript to run this app. JUnit运行时MockRestServiceServer异常:请求模拟顺序是否关键?
优惠活动
大模型
产品
解决方案
定价
更多

JUnit运行时MockRestServiceServer异常:请求模拟顺序是否关键?

请求模拟顺序是否会影响Spring MockRestServiceServer的测试结果?

我已经模拟了两个REST API,但测试时偶尔会触发如下错误;如果调换URL模拟声明的顺序,部分测试能正常运行,但后续还是会失败。想知道请求模拟的顺序是否会影响测试结果?

java.lang.AssertionError: Unexpected request expected:<http://smart-graph-api:8000/api/v1.4/data/write> but was:<http://smart-graph-api:8000/api/v1.4/topology/nodes>
    at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:59)
    at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:122)
    at org.springframework.test.web.client.match.MockRestRequestMatchers.lambda$requestTo$4(MockRestRequestMatchers.java:113)
    at org.springframework.test.web.client.DefaultRequestExpectation.match(DefaultRequestExpectation.java:87)
    at org.springframework.test.web.client.SimpleRequestExpectationManager.matchRequest(SimpleRequestExpectationManager.java:62)
    at org.springframework.test.web.client.AbstractRequestExpectationManager.validateRequest(AbstractRequestExpectationManager.java:91)
    at org.springframework.test.web.client.MockRestServiceServer$MockClientHttpRequestFactory$1.executeInternal(MockRestServiceServer.java:287)
    at org.springframework.mock.http.client.MockClientHttpRequest.execute(MockClientHttpRequest.java:12

是的,MockRestServiceServer默认使用的SimpleRequestExpectationManager是按顺序匹配请求的,这意味着你声明模拟期望的顺序必须和实际代码发送请求的顺序完全一致,否则就会抛出你看到的断言错误。

问题原因

  • 调用MockRestServiceServer.expect()添加的请求期望会按顺序存入队列
  • 实际请求发送时,管理器会从队列头部取出第一个期望匹配,不匹配则直接报错,不会尝试后续期望

解决办法

  • 对齐模拟顺序与实际请求顺序:调整模拟代码的声明顺序,和被测代码发送请求的顺序完全对应
  • 使用无序匹配管理器:如果请求顺序不固定,替换默认管理器,它会遍历所有期望匹配,不要求顺序:
MockRestServiceServer server = MockRestServiceServer.bindTo(restTemplate)
    .expectationManager(new UnorderedRequestExpectationManager())
    .build();
  • 添加精确匹配条件:除了URL,还可以匹配请求方法、请求体、请求头等,减少仅靠URL匹配的冲突

内容的提问来源于stack exchange,提问作者Anju Singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 08:50:07