Add doesExist() to HeaderAssertions for WebTestClient

This commit is contained in:
Sam Brannen 2018-01-25 15:50:19 +01:00
parent 431494096a
commit 165ca12e6d
2 changed files with 35 additions and 1 deletions

View File

@ -32,6 +32,7 @@ import static org.springframework.test.util.AssertionErrors.*;
* *
* @author Rossen Stoyanchev * @author Rossen Stoyanchev
* @author Brian Clozel * @author Brian Clozel
* @author Sam Brannen
* @since 5.0 * @since 5.0
* @see WebTestClient.ResponseSpec#expectHeader() * @see WebTestClient.ResponseSpec#expectHeader()
*/ */
@ -72,6 +73,18 @@ public class HeaderAssertions {
return this.responseSpec; return this.responseSpec;
} }
/**
* Expect that the header with the given name is present.
* @since 5.0.3
*/
public WebTestClient.ResponseSpec doesExist(String name) {
if (!getHeaders().containsKey(name)) {
String message = getMessage(name) + " does not exist";
this.exchangeResult.assertWithDiagnostics(() -> fail(message));
}
return this.responseSpec;
}
/** /**
* Expect that the header with the given name is not present. * Expect that the header with the given name is not present.
*/ */

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2017 the original author or authors. * Copyright 2002-2018 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -37,6 +37,7 @@ import static org.mockito.Mockito.*;
* Unit tests for {@link HeaderAssertions}. * Unit tests for {@link HeaderAssertions}.
* *
* @author Rossen Stoyanchev * @author Rossen Stoyanchev
* @author Sam Brannen
* @since 5.0 * @since 5.0
*/ */
public class HeaderAssertionTests { public class HeaderAssertionTests {
@ -124,6 +125,26 @@ public class HeaderAssertionTests {
} }
} }
@Test
public void doesExist() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
HeaderAssertions assertions = headerAssertions(headers);
// Success
assertions.doesExist("Content-Type");
try {
assertions.doesExist("Framework");
fail("Header should not exist");
}
catch (AssertionError error) {
Throwable cause = error.getCause();
assertNotNull(cause);
assertEquals("Response header 'Framework' does not exist", cause.getMessage());
}
}
@Test @Test
public void doesNotExist() { public void doesNotExist() {
HttpHeaders headers = new HttpHeaders(); HttpHeaders headers = new HttpHeaders();