Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 06563d8

Browse files
committed
Add headerDoesNotExist() to MockRestRequestMatchers
Prior to this commit, one could not test for the absence of a specific HTTP header in a request. This commit adds a headerDoesNotExist() method in MockRestRequestMatchers. Closes spring-projectsgh-23721
1 parent 4dc966b commit 06563d8

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

spring-test/src/main/java/org/springframework/test/web/client/match/MockRestRequestMatchers.java

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,20 @@ public static RequestMatcher header(String name, String... expectedValues) {
185185
};
186186
}
187187

188+
/**
189+
* Assert that the given request header does not exist.
190+
* @since 5.2
191+
*/
192+
public static RequestMatcher headerDoesNotExist(String name) {
193+
return request -> {
194+
List<String> headerValues = request.getHeaders().get(name);
195+
if (headerValues != null) {
196+
fail("Expected header <" + name + "> not to exist, but it exists with values: " +
197+
headerValues);
198+
}
199+
};
200+
}
201+
188202
/**
189203
* Access to request body matchers.
190204
*/

spring-test/src/test/java/org/springframework/test/web/client/match/MockRestRequestMatchersTests.java

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
import java.net.URI;
2020
import java.util.Arrays;
2121
import java.util.Collections;
22+
import java.util.List;
2223

2324
import org.junit.jupiter.api.Test;
2425

@@ -93,6 +94,19 @@ public void header() throws Exception {
9394
MockRestRequestMatchers.header("foo", "bar", "baz").match(this.request);
9495
}
9596

97+
@Test
98+
public void headerDoesNotExist() throws Exception {
99+
MockRestRequestMatchers.headerDoesNotExist(null).match(this.request);
100+
MockRestRequestMatchers.headerDoesNotExist("").match(this.request);
101+
MockRestRequestMatchers.headerDoesNotExist("foo").match(this.request);
102+
103+
List<String> values = Arrays.asList("bar", "baz");
104+
this.request.getHeaders().put("foo", values);
105+
assertThatThrownBy(() -> MockRestRequestMatchers.headerDoesNotExist("foo").match(this.request))
106+
.isInstanceOf(AssertionError.class)
107+
.hasMessage("Expected header <foo> not to exist, but it exists with values: " + values);
108+
}
109+
96110
@Test
97111
public void headerMissing() throws Exception {
98112
assertThatThrownBy(() -> MockRestRequestMatchers.header("foo", "bar").match(this.request))

0 commit comments

Comments
 (0)