Skip to content

Commit e4479c8

Browse files
bclozelrstoyanchev
authored andcommitted
Fix MockHttpServletResponse HTTP status update
Prior to this commit, one could call the setStatus method on this Mock object and update the response's status, even though the sendError method had already been called. According to the HttpServletResponse Javadoc, sendError() methods commit the response; so the response can't be written after that. This commit fixes MockHttpServletResponse's behavior; setStatus methods do not update the status once the response has been committed. Issue: SPR-10414
1 parent 824cb9f commit e4479c8

File tree

2 files changed

+25
-3
lines changed

2 files changed

+25
-3
lines changed

spring-test/src/main/java/org/springframework/mock/web/MockHttpServletResponse.java

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -533,13 +533,17 @@ private void doAddHeaderValue(String name, Object value, boolean replace) {
533533

534534
@Override
535535
public void setStatus(int status) {
536-
this.status = status;
536+
if(!this.isCommitted()) {
537+
this.status = status;
538+
}
537539
}
538540

539541
@Override
540542
public void setStatus(int status, String errorMessage) {
541-
this.status = status;
542-
this.errorMessage = errorMessage;
543+
if(!this.isCommitted()) {
544+
this.status = status;
545+
this.errorMessage = errorMessage;
546+
}
543547
}
544548

545549
@Override

spring-test/src/test/java/org/springframework/mock/web/MockHttpServletResponseTests.java

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -221,4 +221,22 @@ public void locationHeaderUpdatesGetRedirectedUrl() {
221221
assertEquals(redirectUrl, response.getRedirectedUrl());
222222
}
223223

224+
// SPR-10414
225+
226+
@Test
227+
public void modifyStatusAfterSendError() throws IOException {
228+
response.sendError(HttpServletResponse.SC_NOT_FOUND);
229+
response.setStatus(HttpServletResponse.SC_OK);
230+
assertEquals(response.getStatus(),HttpServletResponse.SC_NOT_FOUND);
231+
}
232+
233+
// SPR-10414
234+
235+
@Test
236+
public void modifyStatusMessageAfterSendError() throws IOException {
237+
response.sendError(HttpServletResponse.SC_NOT_FOUND);
238+
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,"Server Error");
239+
assertEquals(response.getStatus(),HttpServletResponse.SC_NOT_FOUND);
240+
}
241+
224242
}

0 commit comments

Comments
 (0)