Skip to content

AbstractRequestExpectationManager fails with "Expectations already declared" when ResponseCreator.createResponse throws an exception [SPR-16132] #20680

@spring-projects-issues

Description

@spring-projects-issues

Eric Pabst opened SPR-16132 and commented

I am trying to test a scenario where an HTTP request fails without getting a response such as a network error, and that failure is handled by making another RestTemplate request. When I provide a ResponseCreator that throws an exception in createResponse, the test fails with "IllegalStateException: Expectations already declared".

(Over-simplified) Code under test

public void makeServiceCall(RestTemplate restTemplate) {
  try {
    restTemplate.getForEntity("/some-service/some-endpoint", String.class);
  }
  catch (Exception e) {
    restTemplate.postForEntity("/reporting-service/report-error", e.toString(), String.class);
  }
}

Test that reproduces the failure:

  @Test
  public void testRestControllerHandlesMessage_FailsWithUnknownException() throws InterruptedException {
    RestTemplate restTemplate = new RestTemplate();
    MockRestServiceServer mockRestServiceServer = MockRestServiceServer.bindTo(restTemplate).build();
    mockRestServiceServer
        .expect(requestTo("/some-service/some-endpoint"))
        .andRespond((request) -> { throw new IllegalStateException("pseudo network error"); });
    mockRestServiceServer
        .expect(requestTo("/reporting-service/report-error"))
        .andExpect(method(POST))
        .andRespond(withSuccess());

    makeServiceCall(restTemplate);
    mockRestServiceServer.verify();
  }

I debugged this and found out that AbstractRequestExpectationManager.validateRequest only adds the request to the requests collection after validateRequestInternal returns normally. Then when validateRequest is called again for the 2nd RestTemplate call it fails because requests is still empty.

All that is needed is to put "requests.add(request);" into a finally block.


Affects: 4.3.12, 5.0.1

Referenced from: pull request #1580, and commits a88c47a, 43d88e4, 295e3b6, 3c07afc

Backported to: 4.3.13

Metadata

Metadata

Assignees

Labels

in: testIssues in the test modulestatus: backportedAn issue that has been backported to maintenance branchestype: bugA general bug

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions