Fold spring-test-mvc sources into spring-test

With spring-test compiling against Servlet 3.0 it is no longer required
to compile Spring MVC Test sources separately (from spring-test).
This commit is contained in:
Rossen Stoyanchev
2013-11-05 11:44:13 -05:00
parent 0eeb6717e0
commit 2e57cf8bfc
137 changed files with 27 additions and 48 deletions

View File

@@ -0,0 +1,45 @@
/*
* Copyright 2004-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.util;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.junit.Test;
/**
* Test fixture for {@link JsonPathExpectationsHelper}.
*
* @author Rossen Stoyanchev
*/
public class JsonPathExpectationsHelperTests {
@Test
public void test() throws Exception {
try {
new JsonPathExpectationsHelper("$.nr").assertValue("{ \"nr\" : 5 }", "5");
fail("Expected exception");
}
catch (AssertionError ex) {
assertEquals("For JSON path $.nr type of value expected:<class java.lang.String> but was:<class java.lang.Integer>",
ex.getMessage());
}
}
}

View File

@@ -0,0 +1,93 @@
/*
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web;
import javax.validation.constraints.NotNull;
import javax.xml.bind.annotation.XmlRootElement;
import org.springframework.util.ObjectUtils;
@XmlRootElement
public class Person {
@NotNull
private String name;
private double someDouble;
private boolean someBoolean;
public Person() {
}
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
public Person setName(String name) {
this.name = name;
return this;
}
public double getSomeDouble() {
return someDouble;
}
public Person setSomeDouble(double someDouble) {
this.someDouble = someDouble;
return this;
}
public boolean isSomeBoolean() {
return someBoolean;
}
public Person setSomeBoolean(boolean someBoolean) {
this.someBoolean = someBoolean;
return this;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof Person)) {
return false;
}
Person otherPerson = (Person) other;
return (ObjectUtils.nullSafeEquals(this.name, otherPerson.name) &&
ObjectUtils.nullSafeEquals(this.someDouble, otherPerson.someDouble) &&
ObjectUtils.nullSafeEquals(this.someBoolean, otherPerson.someBoolean));
}
@Override
public int hashCode() {
return Person.class.hashCode();
}
@Override
public String toString() {
return "Person [name=" + this.name + ", someDouble=" + this.someDouble
+ ", someBoolean=" + this.someBoolean + "]";
}
}

View File

@@ -0,0 +1,102 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.client;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.anything;
import java.net.URI;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.RestTemplate;
/**
* Tests for {@link MockClientHttpRequestFactory}.
*
* @author Rossen Stoyanchev
*/
public class MockClientHttpRequestFactoryTests {
private MockRestServiceServer server;
private ClientHttpRequestFactory factory;
@Before
public void setup() {
RestTemplate restTemplate = new RestTemplate();
this.server = MockRestServiceServer.createServer(restTemplate);
this.factory = restTemplate.getRequestFactory();
}
@Test
public void createRequest() throws Exception {
URI uri = new URI("/foo");
ClientHttpRequest expected = (ClientHttpRequest) this.server.expect(anything());
ClientHttpRequest actual = this.factory.createRequest(uri, HttpMethod.GET);
assertSame(expected, actual);
assertEquals(uri, actual.getURI());
assertEquals(HttpMethod.GET, actual.getMethod());
}
@Test
public void noFurtherRequestsExpected() throws Exception {
try {
this.factory.createRequest(new URI("/foo"), HttpMethod.GET);
}
catch (AssertionError error) {
assertEquals("No further requests expected", error.getMessage());
}
}
@Test
public void verifyZeroExpected() throws Exception {
this.server.verify();
}
@Test
public void verifyExpectedEqualExecuted() throws Exception {
this.server.expect(anything());
this.server.expect(anything());
this.factory.createRequest(new URI("/foo"), HttpMethod.GET);
this.factory.createRequest(new URI("/bar"), HttpMethod.POST);
}
@Test
public void verifyMoreExpected() throws Exception {
this.server.expect(anything());
this.server.expect(anything());
this.factory.createRequest(new URI("/foo"), HttpMethod.GET);
try {
this.server.verify();
}
catch (AssertionError error) {
assertTrue(error.getMessage(), error.getMessage().contains("1 out of 2 were executed"));
}
}
}

View File

@@ -0,0 +1,123 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.client.match;
import static org.hamcrest.Matchers.hasXPath;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.MediaType;
import org.springframework.mock.http.client.MockClientHttpRequest;
import org.springframework.test.web.client.match.ContentRequestMatchers;
import org.springframework.test.web.client.match.MockRestRequestMatchers;
/**
* Tests for {@link ContentRequestMatchers}.
*
* @author Rossen Stoyanchev
*/
public class ContentRequestMatchersTests {
private MockClientHttpRequest request;
@Before
public void setUp() {
this.request = new MockClientHttpRequest();
}
@Test
public void testContentType() throws Exception {
this.request.getHeaders().setContentType(MediaType.APPLICATION_JSON);
MockRestRequestMatchers.content().contentType("application/json").match(this.request);
MockRestRequestMatchers.content().contentType(MediaType.APPLICATION_JSON).match(this.request);
}
@Test(expected=AssertionError.class)
public void testContentTypeNoMatch1() throws Exception {
this.request.getHeaders().setContentType(MediaType.APPLICATION_JSON);
MockRestRequestMatchers.content().contentType("application/xml").match(this.request);
}
@Test(expected=AssertionError.class)
public void testContentTypeNoMatch2() throws Exception {
this.request.getHeaders().setContentType(MediaType.APPLICATION_JSON);
MockRestRequestMatchers.content().contentType(MediaType.APPLICATION_ATOM_XML).match(this.request);
}
@Test
public void testString() throws Exception {
this.request.getBody().write("test".getBytes());
MockRestRequestMatchers.content().string("test").match(this.request);
}
@Test(expected=AssertionError.class)
public void testStringNoMatch() throws Exception {
this.request.getBody().write("test".getBytes());
MockRestRequestMatchers.content().string("Test").match(this.request);
}
@Test
public void testBytes() throws Exception {
byte[] content = "test".getBytes();
this.request.getBody().write(content);
MockRestRequestMatchers.content().bytes(content).match(this.request);
}
@Test(expected=AssertionError.class)
public void testBytesNoMatch() throws Exception {
this.request.getBody().write("test".getBytes());
MockRestRequestMatchers.content().bytes("Test".getBytes()).match(this.request);
}
@Test
public void testXml() throws Exception {
String content = "<foo><bar>baz</bar><bar>bazz</bar></foo>";
this.request.getBody().write(content.getBytes());
MockRestRequestMatchers.content().xml(content).match(this.request);
}
@Test(expected=AssertionError.class)
public void testXmlNoMatch() throws Exception {
this.request.getBody().write("<foo>11</foo>".getBytes());
MockRestRequestMatchers.content().xml("<foo>22</foo>").match(this.request);
}
@Test
public void testNodeMatcher() throws Exception {
String content = "<foo><bar>baz</bar></foo>";
this.request.getBody().write(content.getBytes());
MockRestRequestMatchers.content().node(hasXPath("/foo/bar")).match(this.request);
}
@Test(expected=AssertionError.class)
public void testNodeMatcherNoMatch() throws Exception {
String content = "<foo><bar>baz</bar></foo>";
this.request.getBody().write(content.getBytes());
MockRestRequestMatchers.content().node(hasXPath("/foo/bar/bar")).match(this.request);
}
}

View File

@@ -0,0 +1,93 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.client.match;
import java.io.IOException;
import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.http.client.MockClientHttpRequest;
import org.springframework.test.web.client.match.JsonPathRequestMatchers;
/**
* Tests for {@link JsonPathRequestMatchers}.
*
* @author Rossen Stoyanchev
*/
public class JsonPathRequestMatchersTests {
private static final String RESPONSE_CONTENT = "{\"foo\":\"bar\", \"qux\":[\"baz1\",\"baz2\"]}";
private MockClientHttpRequest request;
@Before
public void setUp() throws IOException {
this.request = new MockClientHttpRequest();
this.request.getBody().write(RESPONSE_CONTENT.getBytes());
}
@Test
public void value() throws Exception {
new JsonPathRequestMatchers("$.foo").value("bar").match(this.request);
}
@Test(expected=AssertionError.class)
public void valueNoMatch() throws Exception {
new JsonPathRequestMatchers("$.foo").value("bogus").match(this.request);
}
@Test
public void valueMatcher() throws Exception {
new JsonPathRequestMatchers("$.foo").value(Matchers.equalTo("bar")).match(this.request);
}
@Test(expected=AssertionError.class)
public void valueMatcherNoMatch() throws Exception {
new JsonPathRequestMatchers("$.foo").value(Matchers.equalTo("bogus")).match(this.request);
}
@Test
public void exists() throws Exception {
new JsonPathRequestMatchers("$.foo").exists().match(this.request);
}
@Test(expected=AssertionError.class)
public void existsNoMatch() throws Exception {
new JsonPathRequestMatchers("$.bogus").exists().match(this.request);
}
@Test
public void doesNotExist() throws Exception {
new JsonPathRequestMatchers("$.bogus").doesNotExist().match(this.request);
}
@Test(expected=AssertionError.class)
public void doesNotExistNoMatch() throws Exception {
new JsonPathRequestMatchers("$.foo").doesNotExist().match(this.request);
}
@Test
public void isArrayMatch() throws Exception {
new JsonPathRequestMatchers("$.qux").isArray().match(this.request);
}
@Test(expected=AssertionError.class)
public void isArrayNoMatch() throws Exception {
new JsonPathRequestMatchers("$.bar").isArray().match(this.request);
}
}

View File

@@ -0,0 +1,139 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.client.match;
import static org.hamcrest.Matchers.containsString;
import java.net.URI;
import java.util.Arrays;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.HttpMethod;
import org.springframework.mock.http.client.MockClientHttpRequest;
import org.springframework.test.web.client.match.MockRestRequestMatchers;
/**
* Tests for {@link MockRestRequestMatchers}.
*
* @author Craig Walls
* @author Rossen Stoyanchev
*/
public class RequestMatchersTests {
private MockClientHttpRequest request;
@Before
public void setUp() {
this.request = new MockClientHttpRequest();
}
@Test
public void requestTo() throws Exception {
this.request.setURI(new URI("http://foo.com/bar"));
MockRestRequestMatchers.requestTo("http://foo.com/bar").match(this.request);
}
@Test(expected=AssertionError.class)
public void requestToNoMatch() throws Exception {
this.request.setURI(new URI("http://foo.com/bar"));
MockRestRequestMatchers.requestTo("http://foo.com/wrong").match(this.request);
}
@Test
public void requestToContains() throws Exception {
this.request.setURI(new URI("http://foo.com/bar"));
MockRestRequestMatchers.requestTo(containsString("bar")).match(this.request);
}
@Test
public void method() throws Exception {
this.request.setMethod(HttpMethod.GET);
MockRestRequestMatchers.method(HttpMethod.GET).match(this.request);
}
@Test(expected=AssertionError.class)
public void methodNoMatch() throws Exception {
this.request.setMethod(HttpMethod.POST);
MockRestRequestMatchers.method(HttpMethod.GET).match(this.request);
}
@Test
public void header() throws Exception {
this.request.getHeaders().put("foo", Arrays.asList("bar", "baz"));
MockRestRequestMatchers.header("foo", "bar", "baz").match(this.request);
}
@Test(expected=AssertionError.class)
public void headerMissing() throws Exception {
MockRestRequestMatchers.header("foo", "bar").match(this.request);
}
@Test(expected=AssertionError.class)
public void headerMissingValue() throws Exception {
this.request.getHeaders().put("foo", Arrays.asList("bar", "baz"));
MockRestRequestMatchers.header("foo", "bad").match(this.request);
}
@SuppressWarnings("unchecked")
@Test
public void headerContains() throws Exception {
this.request.getHeaders().put("foo", Arrays.asList("bar", "baz"));
MockRestRequestMatchers.header("foo", containsString("ba")).match(this.request);
}
@SuppressWarnings("unchecked")
@Test(expected=AssertionError.class)
public void headerContainsWithMissingHeader() throws Exception {
MockRestRequestMatchers.header("foo", containsString("baz")).match(this.request);
}
@SuppressWarnings("unchecked")
@Test(expected=AssertionError.class)
public void headerContainsWithMissingValue() throws Exception {
this.request.getHeaders().put("foo", Arrays.asList("bar", "baz"));
MockRestRequestMatchers.header("foo", containsString("bx")).match(this.request);
}
@Test
public void headers() throws Exception {
this.request.getHeaders().put("foo", Arrays.asList("bar", "baz"));
MockRestRequestMatchers.header("foo", "bar", "baz").match(this.request);
}
@Test(expected=AssertionError.class)
public void headersWithMissingHeader() throws Exception {
MockRestRequestMatchers.header("foo", "bar").match(this.request);
}
@Test(expected=AssertionError.class)
public void headersWithMissingValue() throws Exception {
this.request.getHeaders().put("foo", Arrays.asList("bar"));
MockRestRequestMatchers.header("foo", "bar", "baz").match(this.request);
}
}

View File

@@ -0,0 +1,113 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.client.match;
import java.io.IOException;
import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.http.client.MockClientHttpRequest;
import org.springframework.test.web.client.match.XpathRequestMatchers;
/**
* Tests for {@link XpathRequestMatchers}.
*
* @author Rossen Stoyanchev
*/
public class XpathRequestMatchersTests {
private static final String RESPONSE_CONTENT = "<foo><bar>111</bar><bar>true</bar></foo>";
private MockClientHttpRequest request;
@Before
public void setUp() throws IOException {
this.request = new MockClientHttpRequest();
this.request.getBody().write(RESPONSE_CONTENT.getBytes());
}
@Test
public void testNodeMatcher() throws Exception {
new XpathRequestMatchers("/foo/bar", null).node(Matchers.notNullValue()).match(this.request);
}
@Test(expected=AssertionError.class)
public void testNodeMatcherNoMatch() throws Exception {
new XpathRequestMatchers("/foo/bar", null).node(Matchers.nullValue()).match(this.request);
}
@Test
public void testExists() throws Exception {
new XpathRequestMatchers("/foo/bar", null).exists().match(this.request);
}
@Test(expected=AssertionError.class)
public void testExistsNoMatch() throws Exception {
new XpathRequestMatchers("/foo/Bar", null).exists().match(this.request);
}
@Test
public void testDoesNotExist() throws Exception {
new XpathRequestMatchers("/foo/Bar", null).doesNotExist().match(this.request);
}
@Test(expected=AssertionError.class)
public void testDoesNotExistNoMatch() throws Exception {
new XpathRequestMatchers("/foo/bar", null).doesNotExist().match(this.request);
}
@Test
public void testNodeCount() throws Exception {
new XpathRequestMatchers("/foo/bar", null).nodeCount(2).match(this.request);
}
@Test(expected=AssertionError.class)
public void testNodeCountNoMatch() throws Exception {
new XpathRequestMatchers("/foo/bar", null).nodeCount(1).match(this.request);
}
@Test
public void testString() throws Exception {
new XpathRequestMatchers("/foo/bar[1]", null).string("111").match(this.request);
}
@Test(expected=AssertionError.class)
public void testStringNoMatch() throws Exception {
new XpathRequestMatchers("/foo/bar[1]", null).string("112").match(this.request);
}
@Test
public void testNumber() throws Exception {
new XpathRequestMatchers("/foo/bar[1]", null).number(111.0).match(this.request);
}
@Test(expected=AssertionError.class)
public void testNumberNoMatch() throws Exception {
new XpathRequestMatchers("/foo/bar[1]", null).number(111.1).match(this.request);
}
@Test
public void testBoolean() throws Exception {
new XpathRequestMatchers("/foo/bar[2]", null).booleanValue(true).match(this.request);
}
@Test(expected=AssertionError.class)
public void testBooleanNoMatch() throws Exception {
new XpathRequestMatchers("/foo/bar[2]", null).booleanValue(false).match(this.request);
}
}

View File

@@ -0,0 +1,130 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.client.response;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import org.junit.Test;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.mock.http.client.MockClientHttpResponse;
import org.springframework.test.web.client.response.DefaultResponseCreator;
import org.springframework.test.web.client.response.MockRestResponseCreators;
import org.springframework.util.FileCopyUtils;
/**
* Tests for the {@link MockRestResponseCreators} static factory methods.
*
* @author Rossen Stoyanchev
*/
public class ResponseCreatorsTests {
@Test
public void success() throws Exception {
MockClientHttpResponse response = (MockClientHttpResponse) MockRestResponseCreators.withSuccess().createResponse(null);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertTrue(response.getHeaders().isEmpty());
assertNull(response.getBody());
}
@Test
public void successWithContent() throws Exception {
DefaultResponseCreator responseCreator = MockRestResponseCreators.withSuccess("foo", MediaType.TEXT_PLAIN);
MockClientHttpResponse response = (MockClientHttpResponse) responseCreator.createResponse(null);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals(MediaType.TEXT_PLAIN, response.getHeaders().getContentType());
assertArrayEquals("foo".getBytes(), FileCopyUtils.copyToByteArray(response.getBody()));
}
@Test
public void successWithContentWithoutContentType() throws Exception {
DefaultResponseCreator responseCreator = MockRestResponseCreators.withSuccess("foo", null);
MockClientHttpResponse response = (MockClientHttpResponse) responseCreator.createResponse(null);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertNull(response.getHeaders().getContentType());
assertArrayEquals("foo".getBytes(), FileCopyUtils.copyToByteArray(response.getBody()));
}
@Test
public void created() throws Exception {
URI location = new URI("/foo");
DefaultResponseCreator responseCreator = MockRestResponseCreators.withCreatedEntity(location);
MockClientHttpResponse response = (MockClientHttpResponse) responseCreator.createResponse(null);
assertEquals(HttpStatus.CREATED, response.getStatusCode());
assertEquals(location, response.getHeaders().getLocation());
assertNull(response.getBody());
}
@Test
public void noContent() throws Exception {
DefaultResponseCreator responseCreator = MockRestResponseCreators.withNoContent();
MockClientHttpResponse response = (MockClientHttpResponse) responseCreator.createResponse(null);
assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode());
assertTrue(response.getHeaders().isEmpty());
assertNull(response.getBody());
}
@Test
public void badRequest() throws Exception {
DefaultResponseCreator responseCreator = MockRestResponseCreators.withBadRequest();
MockClientHttpResponse response = (MockClientHttpResponse) responseCreator.createResponse(null);
assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode());
assertTrue(response.getHeaders().isEmpty());
assertNull(response.getBody());
}
@Test
public void unauthorized() throws Exception {
DefaultResponseCreator responseCreator = MockRestResponseCreators.withUnauthorizedRequest();
MockClientHttpResponse response = (MockClientHttpResponse) responseCreator.createResponse(null);
assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
assertTrue(response.getHeaders().isEmpty());
assertNull(response.getBody());
}
@Test
public void serverError() throws Exception {
DefaultResponseCreator responseCreator = MockRestResponseCreators.withServerError();
MockClientHttpResponse response = (MockClientHttpResponse) responseCreator.createResponse(null);
assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode());
assertTrue(response.getHeaders().isEmpty());
assertNull(response.getBody());
}
@Test
public void withStatus() throws Exception {
DefaultResponseCreator responseCreator = MockRestResponseCreators.withStatus(HttpStatus.FORBIDDEN);
MockClientHttpResponse response = (MockClientHttpResponse) responseCreator.createResponse(null);
assertEquals(HttpStatus.FORBIDDEN, response.getStatusCode());
assertTrue(response.getHeaders().isEmpty());
assertNull(response.getBody());
}
}

View File

@@ -0,0 +1,91 @@
/*
* Copyright 2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.client.samples;
import static org.junit.Assert.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.client.MockMvcClientHttpRequestFactory;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* Tests that use a {@link RestTemplate} configured with a
* {@link MockMvcClientHttpRequestFactory} that is in turn configured with a
* {@link MockMvc} instance that uses a {@link WebApplicationContext} loaded by
* the TestContext framework.
*
* @author Rossen Stoyanchev
*/
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration
public class MockMvcClientHttpRequestFactoryTests {
@Autowired
private WebApplicationContext wac;
private RestTemplate restTemplate;
@Before
public void setup() {
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).alwaysExpect(status().isOk()).build();
this.restTemplate = new RestTemplate(new MockMvcClientHttpRequestFactory(mockMvc));
}
@Test
public void test() throws Exception {
String result = this.restTemplate.getForObject("/foo", String.class);
assertEquals("bar", result);
}
@EnableWebMvc
@Configuration
@ComponentScan(basePackageClasses=MockMvcClientHttpRequestFactoryTests.class)
static class MyWebConfig extends WebMvcConfigurerAdapter {
}
@Controller
static class MyController {
@RequestMapping(value="/foo", method=RequestMethod.GET)
@ResponseBody
public String handle() {
return "bar";
}
}
}

View File

@@ -0,0 +1,116 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.client.samples;
import static org.junit.Assert.assertTrue;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
import org.junit.Before;
import org.junit.Test;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.test.web.Person;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.RestTemplate;
/**
* Examples to demonstrate writing client-side REST tests with Spring MVC Test.
* While the tests in this class invoke the RestTemplate directly, in actual
* tests the RestTemplate may likely be invoked indirectly, i.e. through client
* code.
*
* @author Rossen Stoyanchev
*/
public class SampleTests {
private MockRestServiceServer mockServer;
private RestTemplate restTemplate;
@Before
public void setup() {
this.restTemplate = new RestTemplate();
this.mockServer = MockRestServiceServer.createServer(this.restTemplate);
}
@Test
public void performGet() throws Exception {
String responseBody = "{\"name\" : \"Ludwig van Beethoven\", \"someDouble\" : \"1.6035\"}";
this.mockServer.expect(requestTo("/composers/42")).andExpect(method(HttpMethod.GET))
.andRespond(withSuccess(responseBody, MediaType.APPLICATION_JSON));
@SuppressWarnings("unused")
Person ludwig = restTemplate.getForObject("/composers/{id}", Person.class, 42);
// person.getName().equals("Ludwig van Beethoven")
// person.getDouble().equals(1.6035)
this.mockServer.verify();
}
@Test
public void performGetWithResponseBodyFromFile() throws Exception {
Resource responseBody = new ClassPathResource("ludwig.json", this.getClass());
this.mockServer.expect(requestTo("/composers/42")).andExpect(method(HttpMethod.GET))
.andRespond(withSuccess(responseBody, MediaType.APPLICATION_JSON));
@SuppressWarnings("unused")
Person ludwig = restTemplate.getForObject("/composers/{id}", Person.class, 42);
// hotel.getId() == 42
// hotel.getName().equals("Holiday Inn")
this.mockServer.verify();
}
@Test
public void verify() {
this.mockServer.expect(requestTo("/number")).andExpect(method(HttpMethod.GET))
.andRespond(withSuccess("1", MediaType.TEXT_PLAIN));
this.mockServer.expect(requestTo("/number")).andExpect(method(HttpMethod.GET))
.andRespond(withSuccess("2", MediaType.TEXT_PLAIN));
this.mockServer.expect(requestTo("/number")).andExpect(method(HttpMethod.GET))
.andRespond(withSuccess("4", MediaType.TEXT_PLAIN));
this.mockServer.expect(requestTo("/number")).andExpect(method(HttpMethod.GET))
.andRespond(withSuccess("8", MediaType.TEXT_PLAIN));
@SuppressWarnings("unused")
String result = this.restTemplate.getForObject("/number", String.class);
// result == "1"
result = this.restTemplate.getForObject("/number", String.class);
// result == "2"
try {
this.mockServer.verify();
}
catch (AssertionError error) {
assertTrue(error.getMessage(), error.getMessage().contains("2 out of 4 were executed"));
}
}
}

View File

@@ -0,0 +1,103 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.client.samples.matchers;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.Assert.assertTrue;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.content;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter;
import org.springframework.test.web.Person;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.RestTemplate;
/**
* Examples of defining expectations on request content and content type.
*
* @author Rossen Stoyanchev
*
* @see JsonPathRequestMatcherTests
* @see XmlContentRequestMatcherTests
* @see XpathRequestMatcherTests
*/
public class ContentRequestMatcherTests {
private MockRestServiceServer mockServer;
private RestTemplate restTemplate;
@Before
public void setup() {
List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
converters.add(new StringHttpMessageConverter());
converters.add(new MappingJacksonHttpMessageConverter());
this.restTemplate = new RestTemplate();
this.restTemplate.setMessageConverters(converters);
this.mockServer = MockRestServiceServer.createServer(this.restTemplate);
}
@Test
public void contentType() throws Exception {
this.mockServer.expect(content().contentType("application/json;charset=UTF-8")).andRespond(withSuccess());
this.restTemplate.put(new URI("/foo"), new Person());
this.mockServer.verify();
}
@Test
public void contentTypeNoMatch() throws Exception {
this.mockServer.expect(content().contentType("application/json;charset=UTF-8")).andRespond(withSuccess());
try {
this.restTemplate.put(new URI("/foo"), "foo");
}
catch (AssertionError error) {
String message = error.getMessage();
assertTrue(message, message.startsWith("Content type expected:<application/json;charset=UTF-8>"));
}
}
@Test
public void contentAsString() throws Exception {
this.mockServer.expect(content().string("foo")).andRespond(withSuccess());
this.restTemplate.put(new URI("/foo"), "foo");
this.mockServer.verify();
}
@Test
public void contentStringStartsWith() throws Exception {
this.mockServer.expect(content().string(startsWith("foo"))).andRespond(withSuccess());
this.restTemplate.put(new URI("/foo"), "foo123");
this.mockServer.verify();
}
@Test
public void contentAsBytes() throws Exception {
this.mockServer.expect(content().bytes("foo".getBytes())).andRespond(withSuccess());
this.restTemplate.put(new URI("/foo"), "foo");
this.mockServer.verify();
}
}

View File

@@ -0,0 +1,85 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.client.samples.matchers;
import static org.hamcrest.Matchers.containsString;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.header;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter;
import org.springframework.test.web.Person;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.RestTemplate;
/**
* Examples of defining expectations on request headers.
*
* @author Rossen Stoyanchev
*/
public class HeaderRequestMatcherTests {
private static final String RESPONSE_BODY = "{\"name\" : \"Ludwig van Beethoven\", \"someDouble\" : \"1.6035\"}";
private MockRestServiceServer mockServer;
private RestTemplate restTemplate;
@Before
public void setup() {
List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
converters.add(new StringHttpMessageConverter());
converters.add(new MappingJacksonHttpMessageConverter());
this.restTemplate = new RestTemplate();
this.restTemplate.setMessageConverters(converters);
this.mockServer = MockRestServiceServer.createServer(this.restTemplate);
}
@Test
public void testString() throws Exception {
this.mockServer.expect(requestTo("/person/1"))
.andExpect(header("Accept", "application/json, application/*+json"))
.andRespond(withSuccess(RESPONSE_BODY, MediaType.APPLICATION_JSON));
this.restTemplate.getForObject(new URI("/person/1"), Person.class);
this.mockServer.verify();
}
@SuppressWarnings("unchecked")
@Test
public void testStringContains() throws Exception {
this.mockServer.expect(requestTo("/person/1"))
.andExpect(header("Accept", containsString("json")))
.andRespond(withSuccess(RESPONSE_BODY, MediaType.APPLICATION_JSON));
this.restTemplate.getForObject(new URI("/person/1"), Person.class);
this.mockServer.verify();
}
}

View File

@@ -0,0 +1,152 @@
/*
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.client.samples.matchers;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.isIn;
import static org.hamcrest.Matchers.startsWith;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.content;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.jsonPath;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter;
import org.springframework.test.web.Person;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
/**
* Examples of defining expectations on JSON request content with
* <a href="http://goessner.net/articles/JsonPath/">JSONPath</a> expressions.
*
* @author Rossen Stoyanchev
*/
public class JsonPathRequestMatcherTests {
private MockRestServiceServer mockServer;
private RestTemplate restTemplate;
private MultiValueMap<String, Person> people;
@Before
public void setup() {
this.people = new LinkedMultiValueMap<String, Person>();
this.people.add("composers", new Person("Johann Sebastian Bach"));
this.people.add("composers", new Person("Johannes Brahms"));
this.people.add("composers", new Person("Edvard Grieg"));
this.people.add("composers", new Person("Robert Schumann"));
this.people.add("performers", new Person("Vladimir Ashkenazy"));
this.people.add("performers", new Person("Yehudi Menuhin"));
List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
converters.add(new MappingJacksonHttpMessageConverter());
this.restTemplate = new RestTemplate();
this.restTemplate.setMessageConverters(converters);
this.mockServer = MockRestServiceServer.createServer(this.restTemplate);
}
@Test
public void testExists() throws Exception {
this.mockServer.expect(requestTo("/composers"))
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.composers[0]").exists())
.andExpect(jsonPath("$.composers[1]").exists())
.andExpect(jsonPath("$.composers[2]").exists())
.andExpect(jsonPath("$.composers[3]").exists())
.andRespond(withSuccess());
this.restTemplate.put(new URI("/composers"), this.people);
this.mockServer.verify();
}
@Test
public void testDoesNotExist() throws Exception {
this.mockServer.expect(requestTo("/composers"))
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.composers[?(@.name == 'Edvard Grieeeeeeg')]").doesNotExist())
.andExpect(jsonPath("$.composers[?(@.name == 'Robert Schuuuuuuman')]").doesNotExist())
.andExpect(jsonPath("$.composers[-1]").doesNotExist())
.andExpect(jsonPath("$.composers[4]").doesNotExist())
.andRespond(withSuccess());
this.restTemplate.put(new URI("/composers"), this.people);
this.mockServer.verify();
}
@Test
public void testEqualTo() throws Exception {
this.mockServer.expect(requestTo("/composers"))
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.composers[0].name").value("Johann Sebastian Bach"))
.andExpect(jsonPath("$.performers[1].name").value("Yehudi Menuhin"))
.andExpect(jsonPath("$.composers[0].name").value(equalTo("Johann Sebastian Bach"))) // Hamcrest
.andExpect(jsonPath("$.performers[1].name").value(equalTo("Yehudi Menuhin"))) // Hamcrest
.andRespond(withSuccess());
this.restTemplate.put(new URI("/composers"), this.people);
this.mockServer.verify();
}
@Test
public void testHamcrestMatcher() throws Exception {
this.mockServer.expect(requestTo("/composers"))
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.composers[0].name", startsWith("Johann")))
.andExpect(jsonPath("$.performers[0].name", endsWith("Ashkenazy")))
.andExpect(jsonPath("$.performers[1].name", containsString("di Me")))
.andExpect(jsonPath("$.composers[1].name", isIn(Arrays.asList("Johann Sebastian Bach", "Johannes Brahms"))))
.andExpect(jsonPath("$.composers[:3].name", hasItem("Johannes Brahms")))
.andRespond(withSuccess());
this.restTemplate.put(new URI("/composers"), this.people);
this.mockServer.verify();
}
@Test
public void testHamcrestMatcherWithParameterizedJsonPath() throws Exception {
String composerName = "$.composers[%s].name";
String performerName = "$.performers[%s].name";
this.mockServer.expect(requestTo("/composers"))
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath(composerName, 0).value(startsWith("Johann")))
.andExpect(jsonPath(performerName, 0).value(endsWith("Ashkenazy")))
.andExpect(jsonPath(performerName, 1).value(containsString("di Me")))
.andExpect(jsonPath(composerName, 1).value(isIn(Arrays.asList("Johann Sebastian Bach", "Johannes Brahms"))))
.andRespond(withSuccess());
this.restTemplate.put(new URI("/composers"), this.people);
this.mockServer.verify();
}
}

View File

@@ -0,0 +1,133 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.client.samples.matchers;
import static org.hamcrest.Matchers.hasXPath;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.content;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter;
import org.springframework.test.web.Person;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.RestTemplate;
/**
* Examples of defining expectations on XML request content with XMLUnit.
*
* @author Rossen Stoyanchev
*
* @see ContentRequestMatcherTests
* @see XpathRequestMatcherTests
*/
public class XmlContentRequestMatcherTests {
private static final String PEOPLE_XML =
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" +
"<people><composers>" +
"<composer><name>Johann Sebastian Bach</name><someBoolean>false</someBoolean><someDouble>21.0</someDouble></composer>" +
"<composer><name>Johannes Brahms</name><someBoolean>false</someBoolean><someDouble>0.0025</someDouble></composer>" +
"<composer><name>Edvard Grieg</name><someBoolean>false</someBoolean><someDouble>1.6035</someDouble></composer>" +
"<composer><name>Robert Schumann</name><someBoolean>false</someBoolean><someDouble>NaN</someDouble></composer>" +
"</composers></people>";
private MockRestServiceServer mockServer;
private RestTemplate restTemplate;
private PeopleWrapper people;
@Before
public void setup() {
List<Person> composers = Arrays.asList(
new Person("Johann Sebastian Bach").setSomeDouble(21),
new Person("Johannes Brahms").setSomeDouble(.0025),
new Person("Edvard Grieg").setSomeDouble(1.6035),
new Person("Robert Schumann").setSomeDouble(Double.NaN));
this.people = new PeopleWrapper(composers);
List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
converters.add(new Jaxb2RootElementHttpMessageConverter());
this.restTemplate = new RestTemplate();
this.restTemplate.setMessageConverters(converters);
this.mockServer = MockRestServiceServer.createServer(this.restTemplate);
}
@Test
public void testXmlEqualTo() throws Exception {
this.mockServer.expect(requestTo("/composers"))
.andExpect(content().contentType("application/xml"))
.andExpect(content().xml(PEOPLE_XML))
.andRespond(withSuccess());
this.restTemplate.put(new URI("/composers"), this.people);
this.mockServer.verify();
}
@Test
public void testHamcrestNodeMatcher() throws Exception {
this.mockServer.expect(requestTo("/composers"))
.andExpect(content().contentType("application/xml"))
.andExpect(content().node(hasXPath("/people/composers/composer[1]")))
.andRespond(withSuccess());
this.restTemplate.put(new URI("/composers"), this.people);
this.mockServer.verify();
}
@SuppressWarnings("unused")
@XmlRootElement(name="people")
@XmlAccessorType(XmlAccessType.FIELD)
private static class PeopleWrapper {
@XmlElementWrapper(name="composers")
@XmlElement(name="composer")
private List<Person> composers;
public PeopleWrapper() {
}
public PeopleWrapper(List<Person> composers) {
this.composers = composers;
}
public List<Person> getComposers() {
return this.composers;
}
}
}

View File

@@ -0,0 +1,231 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.client.samples.matchers;
import static org.hamcrest.Matchers.closeTo;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.startsWith;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.content;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.xpath;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter;
import org.springframework.test.web.Person;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.RestTemplate;
/**
* Examples of defining expectations on XML request content with XPath expressions.
*
* @author Rossen Stoyanchev
*
* @see ContentRequestMatcherTests
* @see XmlContentRequestMatcherTests
*/
public class XpathRequestMatcherTests {
private static final Map<String, String> NS =
Collections.singletonMap("ns", "http://example.org/music/people");
private MockRestServiceServer mockServer;
private RestTemplate restTemplate;
private PeopleWrapper people;
@Before
public void setup() {
List<Person> composers = Arrays.asList(
new Person("Johann Sebastian Bach").setSomeDouble(21),
new Person("Johannes Brahms").setSomeDouble(.0025),
new Person("Edvard Grieg").setSomeDouble(1.6035),
new Person("Robert Schumann").setSomeDouble(Double.NaN));
List<Person> performers = Arrays.asList(
new Person("Vladimir Ashkenazy").setSomeBoolean(false),
new Person("Yehudi Menuhin").setSomeBoolean(true));
this.people = new PeopleWrapper(composers, performers);
List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
converters.add(new Jaxb2RootElementHttpMessageConverter());
this.restTemplate = new RestTemplate();
this.restTemplate.setMessageConverters(converters);
this.mockServer = MockRestServiceServer.createServer(this.restTemplate);
}
@Test
public void testExists() throws Exception {
String composer = "/ns:people/composers/composer[%s]";
String performer = "/ns:people/performers/performer[%s]";
this.mockServer.expect(requestTo("/composers"))
.andExpect(content().contentType("application/xml"))
.andExpect(xpath(composer, NS, 1).exists())
.andExpect(xpath(composer, NS, 2).exists())
.andExpect(xpath(composer, NS, 3).exists())
.andExpect(xpath(composer, NS, 4).exists())
.andExpect(xpath(performer, NS, 1).exists())
.andExpect(xpath(performer, NS, 2).exists())
.andRespond(withSuccess());
this.restTemplate.put(new URI("/composers"), this.people);
this.mockServer.verify();
}
@Test
public void testDoesNotExist() throws Exception {
String composer = "/ns:people/composers/composer[%s]";
String performer = "/ns:people/performers/performer[%s]";
this.mockServer.expect(requestTo("/composers"))
.andExpect(content().contentType("application/xml"))
.andExpect(xpath(composer, NS, 0).doesNotExist())
.andExpect(xpath(composer, NS, 5).doesNotExist())
.andExpect(xpath(performer, NS, 0).doesNotExist())
.andExpect(xpath(performer, NS, 3).doesNotExist())
.andRespond(withSuccess());
this.restTemplate.put(new URI("/composers"), this.people);
this.mockServer.verify();
}
@Test
public void testString() throws Exception {
String composerName = "/ns:people/composers/composer[%s]/name";
String performerName = "/ns:people/performers/performer[%s]/name";
this.mockServer.expect(requestTo("/composers"))
.andExpect(content().contentType("application/xml"))
.andExpect(xpath(composerName, NS, 1).string("Johann Sebastian Bach"))
.andExpect(xpath(composerName, NS, 2).string("Johannes Brahms"))
.andExpect(xpath(composerName, NS, 3).string("Edvard Grieg"))
.andExpect(xpath(composerName, NS, 4).string("Robert Schumann"))
.andExpect(xpath(performerName, NS, 1).string("Vladimir Ashkenazy"))
.andExpect(xpath(performerName, NS, 2).string("Yehudi Menuhin"))
.andExpect(xpath(composerName, NS, 1).string(equalTo("Johann Sebastian Bach"))) // Hamcrest..
.andExpect(xpath(composerName, NS, 1).string(startsWith("Johann"))) // Hamcrest..
.andExpect(xpath(composerName, NS, 1).string(notNullValue())) // Hamcrest..
.andRespond(withSuccess());
this.restTemplate.put(new URI("/composers"), this.people);
this.mockServer.verify();
}
@Test
public void testNumber() throws Exception {
String composerDouble = "/ns:people/composers/composer[%s]/someDouble";
this.mockServer.expect(requestTo("/composers"))
.andExpect(content().contentType("application/xml"))
.andExpect(xpath(composerDouble, NS, 1).number(21d))
.andExpect(xpath(composerDouble, NS, 2).number(.0025))
.andExpect(xpath(composerDouble, NS, 3).number(1.6035))
.andExpect(xpath(composerDouble, NS, 4).number(Double.NaN))
.andExpect(xpath(composerDouble, NS, 1).number(equalTo(21d))) // Hamcrest..
.andExpect(xpath(composerDouble, NS, 3).number(closeTo(1.6, .01))) // Hamcrest..
.andRespond(withSuccess());
this.restTemplate.put(new URI("/composers"), this.people);
this.mockServer.verify();
}
@Test
public void testBoolean() throws Exception {
String performerBooleanValue = "/ns:people/performers/performer[%s]/someBoolean";
this.mockServer.expect(requestTo("/composers"))
.andExpect(content().contentType("application/xml"))
.andExpect(xpath(performerBooleanValue, NS, 1).booleanValue(false))
.andExpect(xpath(performerBooleanValue, NS, 2).booleanValue(true))
.andRespond(withSuccess());
this.restTemplate.put(new URI("/composers"), this.people);
this.mockServer.verify();
}
@Test
public void testNodeCount() throws Exception {
this.mockServer.expect(requestTo("/composers"))
.andExpect(content().contentType("application/xml"))
.andExpect(xpath("/ns:people/composers/composer", NS).nodeCount(4))
.andExpect(xpath("/ns:people/performers/performer", NS).nodeCount(2))
.andExpect(xpath("/ns:people/composers/composer", NS).nodeCount(equalTo(4))) // Hamcrest..
.andExpect(xpath("/ns:people/performers/performer", NS).nodeCount(equalTo(2))) // Hamcrest..
.andRespond(withSuccess());
this.restTemplate.put(new URI("/composers"), this.people);
this.mockServer.verify();
}
@SuppressWarnings("unused")
@XmlRootElement(name="people", namespace="http://example.org/music/people")
@XmlAccessorType(XmlAccessType.FIELD)
private static class PeopleWrapper {
@XmlElementWrapper(name="composers")
@XmlElement(name="composer")
private List<Person> composers;
@XmlElementWrapper(name="performers")
@XmlElement(name="performer")
private List<Person> performers;
public PeopleWrapper() {
}
public PeopleWrapper(List<Person> composers, List<Person> performers) {
this.composers = composers;
this.performers = performers;
}
public List<Person> getComposers() {
return this.composers;
}
public List<Person> getPerformers() {
return this.performers;
}
}
}

View File

@@ -0,0 +1,116 @@
/*
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.servlet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import javax.servlet.AsyncContext;
import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import static org.mockito.BDDMockito.*;
/**
* Test fixture for {@link DefaultMvcResult}.
*
* @author Rossen Stoyanchev
*/
public class DefaultMvcResultTests {
private static final long DEFAULT_TIMEOUT = 10000L;
private DefaultMvcResult mvcResult;
private CountDownLatch countDownLatch;
@Before
public void setup() {
ExtendedMockHttpServletRequest request = new ExtendedMockHttpServletRequest();
request.setAsyncStarted(true);
this.countDownLatch = mock(CountDownLatch.class);
this.mvcResult = new DefaultMvcResult(request, null);
this.mvcResult.setAsyncResultLatch(this.countDownLatch);
}
@Test
public void getAsyncResultWithTimeout() throws Exception {
long timeout = 1234L;
given(this.countDownLatch.await(timeout, TimeUnit.MILLISECONDS)).willReturn(true);
this.mvcResult.getAsyncResult(timeout);
verify(this.countDownLatch).await(timeout, TimeUnit.MILLISECONDS);
}
@Test
public void getAsyncResultWithTimeoutNegativeOne() throws Exception {
given(this.countDownLatch.await(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS)).willReturn(true);
this.mvcResult.getAsyncResult(-1);
verify(this.countDownLatch).await(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS);
}
@Test
public void getAsyncResultWithoutTimeout() throws Exception {
given(this.countDownLatch.await(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS)).willReturn(true);
this.mvcResult.getAsyncResult();
verify(this.countDownLatch).await(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS);
}
@Test
public void getAsyncResultWithTimeoutZero() throws Exception {
this.mvcResult.getAsyncResult(0);
verifyZeroInteractions(this.countDownLatch);
}
@Test(expected=IllegalStateException.class)
public void getAsyncResultAndTimeOut() throws Exception {
this.mvcResult.getAsyncResult(-1);
verify(this.countDownLatch).await(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS);
}
private static class ExtendedMockHttpServletRequest extends MockHttpServletRequest {
private boolean asyncStarted;
private AsyncContext asyncContext;
public ExtendedMockHttpServletRequest() {
super();
this.asyncContext = mock(AsyncContext.class);
given(this.asyncContext.getTimeout()).willReturn(new Long(DEFAULT_TIMEOUT));
}
@Override
public void setAsyncStarted(boolean asyncStarted) {
this.asyncStarted = asyncStarted;
}
@Override
public boolean isAsyncStarted() {
return this.asyncStarted;
}
@Override
public AsyncContext getAsyncContext() {
return asyncContext;
}
}
}

View File

@@ -0,0 +1,94 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.servlet;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* Test for SPR-10025.
*
* @author Rossen Stoyanchev
*/
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration
public class Spr10025Tests {
@Autowired
private WebApplicationContext wac;
@Autowired
private MockHttpServletRequest servletRequest;
private MockMvc mockMvc;
@Before
public void setup() {
this.mockMvc = webAppContextSetup(this.wac).build();
}
@Test
public void test() throws Exception {
this.servletRequest.setAttribute("foo1", "bar");
this.mockMvc.perform(get("/myUrl").requestAttr("foo2", "bar")).andExpect(status().isOk());
}
@Configuration
@EnableWebMvc
static class WebConfig extends WebMvcConfigurerAdapter {
@Bean
public MyController myController() {
return new MyController();
}
}
@Controller
private static class MyController {
@RequestMapping("/myUrl")
@ResponseBody
public void handle() {
RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
Assert.assertNull(attributes.getAttribute("foo1", RequestAttributes.SCOPE_REQUEST));
Assert.assertNotNull(attributes.getAttribute("foo2", RequestAttributes.SCOPE_REQUEST));
}
}
}

View File

@@ -0,0 +1,94 @@
/*
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.servlet;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.options;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* Tests for SPR-10093 (support for OPTIONS requests).
* @author Arnaud Cogoluègnes
*/
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration
public class Spr10093Tests {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setup() {
this.mockMvc = webAppContextSetup(this.wac).dispatchOptions(true).build();
}
@Test
public void test() throws Exception {
MyController controller = this.wac.getBean(MyController.class);
int initialCount = controller.counter.get();
this.mockMvc.perform(options("/myUrl")).andExpect(status().isOk());
Assert.assertEquals(initialCount+1,controller.counter.get());
}
@Configuration
@EnableWebMvc
static class WebConfig extends WebMvcConfigurerAdapter {
@Bean
public MyController myController() {
return new MyController();
}
}
@Controller
private static class MyController {
private AtomicInteger counter = new AtomicInteger(0);
@RequestMapping(value="/myUrl",method=RequestMethod.OPTIONS)
@ResponseBody
public void handle() {
counter.incrementAndGet();
}
}
}

View File

@@ -0,0 +1,140 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.servlet;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.web.servlet.FlashMap;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
/**
* A stub implementation of the {@link MvcResult} contract.
*
* @author Rossen Stoyanchev
*/
public class StubMvcResult implements MvcResult {
private MockHttpServletRequest request;
private Object handler;
private HandlerInterceptor[] interceptors;
private Exception resolvedException;
private ModelAndView mav;
private FlashMap flashMap;
private MockHttpServletResponse response;
public StubMvcResult(MockHttpServletRequest request,
Object handler,
HandlerInterceptor[] interceptors,
Exception resolvedException,
ModelAndView mav,
FlashMap flashMap,
MockHttpServletResponse response) {
this.request = request;
this.handler = handler;
this.interceptors = interceptors;
this.resolvedException = resolvedException;
this.mav = mav;
this.flashMap = flashMap;
this.response = response;
}
@Override
public MockHttpServletRequest getRequest() {
return request;
}
@Override
public Object getHandler() {
return handler;
}
@Override
public HandlerInterceptor[] getInterceptors() {
return interceptors;
}
@Override
public Exception getResolvedException() {
return resolvedException;
}
@Override
public ModelAndView getModelAndView() {
return mav;
}
@Override
public FlashMap getFlashMap() {
return flashMap;
}
@Override
public MockHttpServletResponse getResponse() {
return response;
}
public ModelAndView getMav() {
return mav;
}
public void setMav(ModelAndView mav) {
this.mav = mav;
}
public void setRequest(MockHttpServletRequest request) {
this.request = request;
}
public void setHandler(Object handler) {
this.handler = handler;
}
public void setInterceptors(HandlerInterceptor[] interceptors) {
this.interceptors = interceptors;
}
public void setResolvedException(Exception resolvedException) {
this.resolvedException = resolvedException;
}
public void setFlashMap(FlashMap flashMap) {
this.flashMap = flashMap;
}
public void setResponse(MockHttpServletResponse response) {
this.response = response;
}
@Override
public Object getAsyncResult() {
return null;
}
@Override
public Object getAsyncResult(long timeout) {
return null;
}
}

View File

@@ -0,0 +1,414 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.servlet.request;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.security.Principal;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.mock.web.MockServletContext;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.servlet.FlashMap;
import org.springframework.web.servlet.support.SessionFlashMapManager;
/**
* Tests building a MockHttpServletRequest with {@link MockHttpServletRequestBuilder}.
*
* @author Rossen Stoyanchev
*/
public class MockHttpServletRequestBuilderTests {
private MockHttpServletRequestBuilder builder;
private ServletContext servletContext;
@Before
public void setUp() throws Exception {
this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, "/foo/bar");
servletContext = new MockServletContext();
}
@Test
public void method() {
MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
assertEquals("GET", request.getMethod());
}
@Test
public void uri() throws Exception {
String uri = "https://java.sun.com:8080/javase/6/docs/api/java/util/BitSet.html?foo=bar#and(java.util.BitSet)";
this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, uri);
MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
assertEquals("https", request.getScheme());
assertEquals("foo=bar", request.getQueryString());
assertEquals("java.sun.com", request.getServerName());
assertEquals(8080, request.getServerPort());
assertEquals("/javase/6/docs/api/java/util/BitSet.html", request.getRequestURI());
assertEquals("https://java.sun.com:8080/javase/6/docs/api/java/util/BitSet.html",
request.getRequestURL().toString());
}
@Test
public void requestUriWithEncoding() throws Exception {
this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, "/foo bar");
MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
assertEquals("/foo%20bar", request.getRequestURI());
}
@Test
public void contextPathEmpty() throws Exception {
this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, "/foo");
MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
assertEquals("", request.getContextPath());
assertEquals("", request.getServletPath());
assertEquals("/foo", request.getPathInfo());
}
@Test
public void contextPathServletPathEmpty() throws Exception {
this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, "/travel/hotels/42");
this.builder.contextPath("/travel");
MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
assertEquals("/travel", request.getContextPath());
assertEquals("", request.getServletPath());
assertEquals("/hotels/42", request.getPathInfo());
}
@Test
public void contextPathServletPath() throws Exception {
this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, "/travel/main/hotels/42");
this.builder.contextPath("/travel");
this.builder.servletPath("/main");
MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
assertEquals("/travel", request.getContextPath());
assertEquals("/main", request.getServletPath());
assertEquals("/hotels/42", request.getPathInfo());
}
@Test
public void contextPathServletPathInfoEmpty() throws Exception {
this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, "/travel/hotels/42");
this.builder.contextPath("/travel");
this.builder.servletPath("/hotels/42");
MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
assertEquals("/travel", request.getContextPath());
assertEquals("/hotels/42", request.getServletPath());
assertNull(request.getPathInfo());
}
@Test
public void contextPathServletPathInfo() throws Exception {
this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, "/");
this.builder.servletPath("/index.html");
this.builder.pathInfo(null);
MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
assertEquals("", request.getContextPath());
assertEquals("/index.html", request.getServletPath());
assertNull(request.getPathInfo());
}
@Test
public void contextPathServletPathInvalid() throws Exception {
testContextPathServletPathInvalid("/Foo", "", "requestURI [/foo/bar] does not start with contextPath [/Foo]");
testContextPathServletPathInvalid("foo", "", "Context path must start with a '/'");
testContextPathServletPathInvalid("/foo/", "", "Context path must not end with a '/'");
testContextPathServletPathInvalid("/foo", "/Bar", "Invalid servletPath [/Bar] for requestURI [/foo/bar]");
testContextPathServletPathInvalid("/foo", "bar", "Servlet path must start with a '/'");
testContextPathServletPathInvalid("/foo", "/bar/", "Servlet path must not end with a '/'");
}
private void testContextPathServletPathInvalid(String contextPath, String servletPath, String message) {
try {
this.builder.contextPath(contextPath);
this.builder.servletPath(servletPath);
this.builder.buildRequest(this.servletContext);
}
catch (IllegalArgumentException ex) {
assertEquals(message, ex.getMessage());
}
}
@Test
public void requestUriAndFragment() throws Exception {
this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, "/foo#bar");
MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
assertEquals("/foo", request.getRequestURI());
}
@Test
public void requestParameter() {
this.builder.param("foo", "bar", "baz");
MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
Map<String, String[]> parameterMap = request.getParameterMap();
assertArrayEquals(new String[]{"bar", "baz"}, parameterMap.get("foo"));
}
@Test
public void requestParameterFromQuery() throws Exception {
this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, "/?foo=bar&foo=baz");
MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
Map<String, String[]> parameterMap = request.getParameterMap();
assertArrayEquals(new String[]{"bar", "baz"}, parameterMap.get("foo"));
assertEquals("foo=bar&foo=baz", request.getQueryString());
}
@Test
public void requestParameterFromQueryList() throws Exception {
this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, "/?foo[0]=bar&foo[1]=baz");
MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
assertEquals("foo[0]=bar&foo[1]=baz", request.getQueryString());
assertEquals("bar", request.getParameter("foo[0]"));
assertEquals("baz", request.getParameter("foo[1]"));
}
@Test
public void requestParameterFromQueryWithEncoding() throws Exception {
this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, "/?foo={value}", "bar=baz");
MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
assertEquals("foo=bar=baz", request.getQueryString());
assertEquals("bar=baz", request.getParameter("foo"));
}
// SPR-11043
@Test
public void requestParameterFromQueryNull() throws Exception {
this.builder = new MockHttpServletRequestBuilder(HttpMethod.GET, "/?foo");
MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
Map<String, String[]> parameterMap = request.getParameterMap();
assertArrayEquals(new String[]{null}, parameterMap.get("foo"));
assertEquals("foo", request.getQueryString());
}
@Test
public void acceptHeader() throws Exception {
this.builder.accept(MediaType.TEXT_HTML, MediaType.APPLICATION_XML);
MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
List<String> accept = Collections.list(request.getHeaders("Accept"));
List<MediaType> result = MediaType.parseMediaTypes(accept.get(0));
assertEquals(1, accept.size());
assertEquals("text/html", result.get(0).toString());
assertEquals("application/xml", result.get(1).toString());
}
@Test
public void contentType() throws Exception {
this.builder.contentType(MediaType.TEXT_HTML);
MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
String contentType = request.getContentType();
List<String> contentTypes = Collections.list(request.getHeaders("Content-Type"));
assertEquals("text/html", contentType);
assertEquals(1, contentTypes.size());
assertEquals("text/html", contentTypes.get(0));
}
@Test
public void body() throws Exception {
byte[] body = "Hello World".getBytes("UTF-8");
this.builder.content(body);
MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
byte[] result = FileCopyUtils.copyToByteArray(request.getInputStream());
assertArrayEquals(body, result);
}
@Test
public void header() throws Exception {
this.builder.header("foo", "bar", "baz");
MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
List<String> headers = Collections.list(request.getHeaders("foo"));
assertEquals(2, headers.size());
assertEquals("bar", headers.get(0));
assertEquals("baz", headers.get(1));
}
@Test
public void headers() throws Exception {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
httpHeaders.put("foo", Arrays.asList("bar", "baz"));
this.builder.headers(httpHeaders);
MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
List<String> headers = Collections.list(request.getHeaders("foo"));
assertEquals(2, headers.size());
assertEquals("bar", headers.get(0));
assertEquals("baz", headers.get(1));
assertEquals(MediaType.APPLICATION_JSON.toString(), request.getHeader("Content-Type"));
}
@Test
public void cookie() throws Exception {
Cookie cookie1 = new Cookie("foo", "bar");
Cookie cookie2 = new Cookie("baz", "qux");
this.builder.cookie(cookie1, cookie2);
MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
Cookie[] cookies = request.getCookies();
assertEquals(2, cookies.length);
assertEquals("foo", cookies[0].getName());
assertEquals("bar", cookies[0].getValue());
assertEquals("baz", cookies[1].getName());
assertEquals("qux", cookies[1].getValue());
}
@Test
public void locale() throws Exception {
Locale locale = new Locale("nl", "nl");
this.builder.locale(locale);
MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
assertEquals(locale, request.getLocale());
}
@Test
public void characterEncoding() throws Exception {
String encoding = "UTF-8";
this.builder.characterEncoding(encoding);
MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
assertEquals(encoding, request.getCharacterEncoding());
}
@Test
public void requestAttribute() throws Exception {
this.builder.requestAttr("foo", "bar");
MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
assertEquals("bar", request.getAttribute("foo"));
}
@Test
public void sessionAttribute() throws Exception {
this.builder.sessionAttr("foo", "bar");
MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
assertEquals("bar", request.getSession().getAttribute("foo"));
}
@Test
public void sessionAttributes() throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
map.put("foo", "bar");
this.builder.sessionAttrs(map);
MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
assertEquals("bar", request.getSession().getAttribute("foo"));
}
@Test
public void session() throws Exception {
MockHttpSession session = new MockHttpSession(this.servletContext);
session.setAttribute("foo", "bar");
this.builder.session(session);
this.builder.sessionAttr("baz", "qux");
MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
assertEquals(session, request.getSession());
assertEquals("bar", request.getSession().getAttribute("foo"));
assertEquals("qux", request.getSession().getAttribute("baz"));
}
@Test
public void flashAttribute() throws Exception {
this.builder.flashAttr("foo", "bar");
MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
FlashMap flashMap = new SessionFlashMapManager().retrieveAndUpdate(request, null);
assertNotNull(flashMap);
assertEquals("bar", flashMap.get("foo"));
}
@Test
public void principal() throws Exception {
User user = new User();
this.builder.principal(user);
MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
assertEquals(user, request.getUserPrincipal());
}
private final class User implements Principal {
@Override
public String getName() {
return "Foo";
}
}
}

View File

@@ -0,0 +1,46 @@
/*
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.servlet.request;
import org.junit.Test;
import org.springframework.http.HttpMethod;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockServletContext;
import static org.junit.Assert.*;
/**
* @author Rossen Stoyanchev
*/
public class MockMultipartHttpServletRequestBuilderTests {
@Test
public void test() {
MockHttpServletRequestBuilder parent = new MockHttpServletRequestBuilder(HttpMethod.GET, "/");
parent.characterEncoding("UTF-8");
Object result = new MockMultipartHttpServletRequestBuilder("/fileUpload").merge(parent);
assertNotNull(result);
assertEquals(MockMultipartHttpServletRequestBuilder.class, result.getClass());
MockMultipartHttpServletRequestBuilder builder = (MockMultipartHttpServletRequestBuilder) result;
MockHttpServletRequest request = builder.buildRequest(new MockServletContext());
assertEquals("UTF-8", request.getCharacterEncoding());
}
}

View File

@@ -0,0 +1,91 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.servlet.result;
import org.hamcrest.Matchers;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.web.servlet.StubMvcResult;
import org.springframework.test.web.servlet.result.ContentResultMatchers;
/**
* @author Rossen Stoyanchev
*/
public class ContentResultMatchersTests {
@Test
public void typeMatches() throws Exception {
new ContentResultMatchers().contentType("application/json;charset=UTF-8").match(getStubMvcResult());
}
@Test(expected=AssertionError.class)
public void typeNoMatch() throws Exception {
new ContentResultMatchers().contentType("text/plain").match(getStubMvcResult());
}
@Test
public void encoding() throws Exception {
new ContentResultMatchers().encoding("UTF-8").match(getStubMvcResult());
}
@Test(expected=AssertionError.class)
public void encodingNoMatch() throws Exception {
new ContentResultMatchers().encoding("ISO-8859-1").match(getStubMvcResult());
}
@Test
public void string() throws Exception {
new ContentResultMatchers().string(new String(CONTENT.getBytes("UTF-8"))).match(getStubMvcResult());
}
@Test(expected=AssertionError.class)
public void stringNoMatch() throws Exception {
new ContentResultMatchers().encoding("bogus").match(getStubMvcResult());
}
@Test
public void stringMatcher() throws Exception {
String content = new String(CONTENT.getBytes("UTF-8"));
new ContentResultMatchers().string(Matchers.equalTo(content)).match(getStubMvcResult());
}
@Test(expected=AssertionError.class)
public void stringMatcherNoMatch() throws Exception {
new ContentResultMatchers().string(Matchers.equalTo("bogus")).match(getStubMvcResult());
}
@Test
public void bytes() throws Exception {
new ContentResultMatchers().bytes(CONTENT.getBytes("UTF-8")).match(getStubMvcResult());
}
@Test(expected=AssertionError.class)
public void bytesNoMatch() throws Exception {
new ContentResultMatchers().bytes("bogus".getBytes()).match(getStubMvcResult());
}
private static final String CONTENT = "{\"foo\":\"bar\"}";
private StubMvcResult getStubMvcResult() throws Exception {
MockHttpServletResponse response = new MockHttpServletResponse();
response.addHeader("Content-Type", "application/json; charset=UTF-8");
response.getWriter().print(new String(CONTENT.getBytes("UTF-8")));
return new StubMvcResult(null, null, null, null, null, null, response);
}
}

View File

@@ -0,0 +1,56 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.servlet.result;
import org.junit.Test;
import org.springframework.test.web.servlet.StubMvcResult;
import org.springframework.test.web.servlet.result.FlashAttributeResultMatchers;
import org.springframework.web.servlet.FlashMap;
/**
* @author Craig Walls
*/
public class FlashAttributeResultMatchersTests {
@Test
public void attributeExists() throws Exception {
new FlashAttributeResultMatchers().attributeExists("good").match(getStubMvcResult());
}
@Test(expected=AssertionError.class)
public void attributeExists_doesntExist() throws Exception {
new FlashAttributeResultMatchers().attributeExists("bad").match(getStubMvcResult());
}
@Test
public void attribute() throws Exception {
new FlashAttributeResultMatchers().attribute("good", "good").match(getStubMvcResult());
}
@Test(expected=AssertionError.class)
public void attribute_incorrectValue() throws Exception {
new FlashAttributeResultMatchers().attribute("good", "not good").match(getStubMvcResult());
}
private StubMvcResult getStubMvcResult() {
FlashMap flashMap = new FlashMap();
flashMap.put("good", "good");
StubMvcResult mvcResult = new StubMvcResult(null, null, null, null, null, flashMap, null);
return mvcResult;
}
}

View File

@@ -0,0 +1,92 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.servlet.result;
import org.hamcrest.Matchers;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.web.servlet.StubMvcResult;
import org.springframework.test.web.servlet.result.JsonPathResultMatchers;
/**
* Tests for {@link JsonPathResultMatchers}.
*
* @author Rossen Stoyanchev
*/
public class JsonPathResultMatchersTests {
@Test
public void value() throws Exception {
new JsonPathResultMatchers("$.foo").value("bar").match(getStubMvcResult());
}
@Test(expected=AssertionError.class)
public void valueNoMatch() throws Exception {
new JsonPathResultMatchers("$.foo").value("bogus").match(getStubMvcResult());
}
@Test
public void valueMatcher() throws Exception {
new JsonPathResultMatchers("$.foo").value(Matchers.equalTo("bar")).match(getStubMvcResult());
}
@Test(expected=AssertionError.class)
public void valueMatcherNoMatch() throws Exception {
new JsonPathResultMatchers("$.foo").value(Matchers.equalTo("bogus")).match(getStubMvcResult());
}
@Test
public void exists() throws Exception {
new JsonPathResultMatchers("$.foo").exists().match(getStubMvcResult());
}
@Test(expected=AssertionError.class)
public void existsNoMatch() throws Exception {
new JsonPathResultMatchers("$.bogus").exists().match(getStubMvcResult());
}
@Test
public void doesNotExist() throws Exception {
new JsonPathResultMatchers("$.bogus").doesNotExist().match(getStubMvcResult());
}
@Test(expected=AssertionError.class)
public void doesNotExistNoMatch() throws Exception {
new JsonPathResultMatchers("$.foo").doesNotExist().match(getStubMvcResult());
}
@Test
public void isArrayMatch() throws Exception {
new JsonPathResultMatchers("$.qux").isArray().match(getStubMvcResult());
}
@Test(expected=AssertionError.class)
public void isArrayNoMatch() throws Exception {
new JsonPathResultMatchers("$.bar").isArray().match(getStubMvcResult());
}
private static final String RESPONSE_CONTENT = "{\"foo\":\"bar\", \"qux\":[\"baz1\",\"baz2\"]}";
private StubMvcResult getStubMvcResult() throws Exception {
MockHttpServletResponse response = new MockHttpServletResponse();
response.addHeader("Content-Type", "application/json");
response.getWriter().print(new String(RESPONSE_CONTENT.getBytes("ISO-8859-1")));
return new StubMvcResult(null, null, null, null, null, null, response);
}
}

View File

@@ -0,0 +1,77 @@
/*
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.servlet.result;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.web.servlet.StubMvcResult;
/**
* @author Brian Clozel
*/
public class MockMvcResultMatchersTests {
@Test
public void testRedirect() throws Exception {
MockMvcResultMatchers.redirectedUrl("/resource/1")
.match(getRedirectedUrlStubMvcResult("/resource/1"));
}
@Test
public void testRedirectPattern() throws Exception {
MockMvcResultMatchers.redirectedUrlPattern("/resource/*")
.match(getRedirectedUrlStubMvcResult("/resource/1"));
}
@Test( expected = java.lang.AssertionError.class)
public void testFailRedirectPattern() throws Exception {
MockMvcResultMatchers.redirectedUrlPattern("/resource/")
.match(getRedirectedUrlStubMvcResult("/resource/1"));
}
@Test
public void testForward() throws Exception {
MockMvcResultMatchers.forwardedUrl("/api/resource/1")
.match(getForwardedUrlStubMvcResult("/api/resource/1"));
}
@Test
public void testForwardEscapedChars() throws Exception {
MockMvcResultMatchers.forwardedUrl("/api/resource/1?arg=value")
.match(getForwardedUrlStubMvcResult("/api/resource/1?arg=value"));
}
@Test
public void testForwardPattern() throws Exception {
MockMvcResultMatchers.forwardedUrlPattern("/api/**/?")
.match(getForwardedUrlStubMvcResult("/api/resource/1"));
}
private StubMvcResult getRedirectedUrlStubMvcResult(String redirectUrl) throws Exception {
MockHttpServletResponse response = new MockHttpServletResponse();
response.sendRedirect(redirectUrl);
StubMvcResult mvcResult = new StubMvcResult(null, null, null, null, null, null, response);
return mvcResult;
}
private StubMvcResult getForwardedUrlStubMvcResult(String forwardedUrl) {
MockHttpServletResponse response = new MockHttpServletResponse();
response.setForwardedUrl(forwardedUrl);
StubMvcResult mvcResult = new StubMvcResult(null, null, null, null, null, null, response);
return mvcResult;
}
}

View File

@@ -0,0 +1,151 @@
/*
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.servlet.result;
import static org.hamcrest.Matchers.is;
import java.util.Date;
import org.junit.Before;
import org.junit.Test;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.StubMvcResult;
import org.springframework.test.web.servlet.result.ModelResultMatchers;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.BindingResult;
import org.springframework.web.servlet.ModelAndView;
/**
* @author Craig Walls
*/
public class ModelResultMatchersTests {
private ModelResultMatchers matchers;
private MvcResult mvcResult;
private MvcResult mvcResultWithError;
@Before
public void setUp() throws Exception {
this.matchers = new ModelResultMatchers();
ModelAndView mav = new ModelAndView("view", "good", "good");
BindingResult bindingResult = new BeanPropertyBindingResult("good", "good");
mav.addObject(BindingResult.MODEL_KEY_PREFIX + "good", bindingResult);
this.mvcResult = getMvcResult(mav);
Date date = new Date();
BindingResult bindingResultWithError = new BeanPropertyBindingResult(date, "date");
bindingResultWithError.rejectValue("time", "error");
ModelAndView mavWithError = new ModelAndView("view", "good", "good");
mavWithError.addObject("date", date);
mavWithError.addObject(BindingResult.MODEL_KEY_PREFIX + "date", bindingResultWithError);
this.mvcResultWithError = getMvcResult(mavWithError);
}
@Test
public void attributeExists() throws Exception {
this.matchers.attributeExists("good").match(this.mvcResult);
}
@Test(expected=AssertionError.class)
public void attributeExists_doesNotExist() throws Exception {
this.matchers.attributeExists("bad").match(this.mvcResult);
}
@Test
public void attributeDoesNotExist() throws Exception {
this.matchers.attributeDoesNotExist("bad").match(this.mvcResult);
}
@Test(expected=AssertionError.class)
public void attributeDoesNotExist_doesExist() throws Exception {
this.matchers.attributeDoesNotExist("good").match(this.mvcResultWithError);
}
@Test
public void attribute_equal() throws Exception {
this.matchers.attribute("good", is("good")).match(this.mvcResult);
}
@Test(expected=AssertionError.class)
public void attribute_notEqual() throws Exception {
this.matchers.attribute("good", is("bad")).match(this.mvcResult);
}
@Test
public void hasNoErrors() throws Exception {
this.matchers.hasNoErrors().match(this.mvcResult);
}
@Test(expected=AssertionError.class)
public void hasNoErrors_withErrors() throws Exception {
this.matchers.hasNoErrors().match(this.mvcResultWithError);
}
@Test
public void attributeHasErrors() throws Exception {
this.matchers.attributeHasErrors("date").match(this.mvcResultWithError);
}
@Test(expected=AssertionError.class)
public void attributeHasErrors_withoutErrors() throws Exception {
this.matchers.attributeHasErrors("good").match(this.mvcResultWithError);
}
@Test
public void attributeHasNoErrors() throws Exception {
this.matchers.attributeHasNoErrors("good").match(this.mvcResult);
}
@Test(expected=AssertionError.class)
public void attributeHasNoErrors_withoutAttribute() throws Exception {
this.matchers.attributeHasNoErrors("missing").match(this.mvcResultWithError);
}
@Test(expected=AssertionError.class)
public void attributeHasNoErrors_withErrors() throws Exception {
this.matchers.attributeHasNoErrors("date").match(this.mvcResultWithError);
}
@Test
public void attributeHasFieldErrors() throws Exception {
this.matchers.attributeHasFieldErrors("date", "time").match(this.mvcResultWithError);
}
@Test(expected=AssertionError.class)
public void attributeHasFieldErrors_withoutAttribute() throws Exception {
this.matchers.attributeHasFieldErrors("missing", "bad").match(this.mvcResult);
}
@Test(expected=AssertionError.class)
public void attributeHasFieldErrors_withoutErrorsForAttribute() throws Exception {
this.matchers.attributeHasFieldErrors("date", "time").match(this.mvcResult);
}
@Test(expected=AssertionError.class)
public void attributeHasFieldErrors_withoutErrorsForField() throws Exception {
this.matchers.attributeHasFieldErrors("date", "good", "time").match(this.mvcResultWithError);
}
private MvcResult getMvcResult(ModelAndView modelAndView) {
return new StubMvcResult(null, null, null, null, modelAndView, null, null);
}
}

View File

@@ -0,0 +1,250 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.servlet.result;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.Cookie;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.web.servlet.StubMvcResult;
import org.springframework.test.web.servlet.result.PrintingResultHandler;
import org.springframework.util.Assert;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.FlashMap;
import org.springframework.web.servlet.ModelAndView;
/**
* Tests for {@link PrintingResultHandler}.
*
* @author Rossen Stoyanchev
*/
public class PrintingResultHandlerTests {
private TestPrintingResultHandler handler;
private MockHttpServletRequest request;
private MockHttpServletResponse response;
private StubMvcResult mvcResult;
@Before
public void setup() {
this.handler = new TestPrintingResultHandler();
this.request = new MockHttpServletRequest("GET", "/") {
@Override
public boolean isAsyncStarted() {
return false;
}
};
this.response = new MockHttpServletResponse();
this.mvcResult = new StubMvcResult(this.request, null, null, null, null, null, this.response);
}
@Test
public void testPrintRequest() throws Exception {
this.request.addParameter("param", "paramValue");
this.request.addHeader("header", "headerValue");
this.handler.handle(this.mvcResult);
HttpHeaders headers = new HttpHeaders();
headers.set("header", "headerValue");
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
params.add("param", "paramValue");
assertValue("MockHttpServletRequest", "HTTP Method", this.request.getMethod());
assertValue("MockHttpServletRequest", "Request URI", this.request.getRequestURI());
assertValue("MockHttpServletRequest", "Parameters", params);
assertValue("MockHttpServletRequest", "Headers", headers);
}
@Test
public void testPrintResponse() throws Exception {
this.response.setStatus(400, "error");
this.response.addHeader("header", "headerValue");
this.response.setContentType("text/plain");
this.response.getWriter().print("content");
this.response.setForwardedUrl("redirectFoo");
this.response.sendRedirect("/redirectFoo");
this.response.addCookie(new Cookie("cookie", "cookieValue"));
this.handler.handle(this.mvcResult);
HttpHeaders headers = new HttpHeaders();
headers.set("header", "headerValue");
headers.setContentType(MediaType.TEXT_PLAIN);
headers.setLocation(new URI("/redirectFoo"));
assertValue("MockHttpServletResponse", "Status", this.response.getStatus());
assertValue("MockHttpServletResponse", "Error message", response.getErrorMessage());
assertValue("MockHttpServletResponse", "Headers", headers);
assertValue("MockHttpServletResponse", "Content type", this.response.getContentType());
assertValue("MockHttpServletResponse", "Body", this.response.getContentAsString());
assertValue("MockHttpServletResponse", "Forwarded URL", this.response.getForwardedUrl());
assertValue("MockHttpServletResponse", "Redirected URL", this.response.getRedirectedUrl());
}
@Test
public void testPrintHandlerNull() throws Exception {
StubMvcResult mvcResult = new StubMvcResult(this.request, null, null, null, null, null, this.response);
this.handler.handle(mvcResult);
assertValue("Handler", "Type", null);
}
@Test
public void testPrintHandler() throws Exception {
this.mvcResult.setHandler(new Object());
this.handler.handle(this.mvcResult);
assertValue("Handler", "Type", Object.class.getName());
}
@Test
public void testPrintHandlerMethod() throws Exception {
HandlerMethod handlerMethod = new HandlerMethod(this, "handle");
this.mvcResult.setHandler(handlerMethod);
this.handler.handle(mvcResult);
assertValue("Handler", "Type", this.getClass().getName());
assertValue("Handler", "Method", handlerMethod);
}
@Test
public void testResolvedExceptionNull() throws Exception {
this.handler.handle(this.mvcResult);
assertValue("Resolved Exception", "Type", null);
}
@Test
public void testResolvedException() throws Exception {
this.mvcResult.setResolvedException(new Exception());
this.handler.handle(this.mvcResult);
assertValue("Resolved Exception", "Type", Exception.class.getName());
}
@Test
public void testModelAndViewNull() throws Exception {
this.handler.handle(this.mvcResult);
assertValue("ModelAndView", "View name", null);
assertValue("ModelAndView", "View", null);
assertValue("ModelAndView", "Model", null);
}
@Test
public void testModelAndView() throws Exception {
BindException bindException = new BindException(new Object(), "target");
bindException.reject("errorCode");
ModelAndView mav = new ModelAndView("viewName");
mav.addObject("attrName", "attrValue");
mav.addObject(BindingResult.MODEL_KEY_PREFIX + "attrName", bindException);
this.mvcResult.setMav(mav);
this.handler.handle(this.mvcResult);
assertValue("ModelAndView", "View name", "viewName");
assertValue("ModelAndView", "View", null);
assertValue("ModelAndView", "Attribute", "attrName");
assertValue("ModelAndView", "value", "attrValue");
assertValue("ModelAndView", "errors", bindException.getAllErrors());
}
@Test
public void testFlashMapNull() throws Exception {
this.handler.handle(mvcResult);
assertValue("FlashMap", "Type", null);
}
@Test
public void testFlashMap() throws Exception {
FlashMap flashMap = new FlashMap();
flashMap.put("attrName", "attrValue");
this.request.setAttribute(DispatcherServlet.class.getName() + ".OUTPUT_FLASH_MAP", flashMap);
this.handler.handle(this.mvcResult);
assertValue("FlashMap", "Attribute", "attrName");
assertValue("FlashMap", "value", "attrValue");
}
private void assertValue(String heading, String label, Object value) {
Map<String, Map<String, Object>> printedValues = this.handler.getPrinter().printedValues;
assertTrue("Heading " + heading + " not printed", printedValues.containsKey(heading));
assertEquals(value, printedValues.get(heading).get(label));
}
private static class TestPrintingResultHandler extends PrintingResultHandler {
public TestPrintingResultHandler() {
super(new TestResultValuePrinter());
}
@Override
public TestResultValuePrinter getPrinter() {
return (TestResultValuePrinter) super.getPrinter();
}
private static class TestResultValuePrinter implements ResultValuePrinter {
private String printedHeading;
private Map<String, Map<String, Object>> printedValues = new HashMap<String, Map<String, Object>>();
@Override
public void printHeading(String heading) {
this.printedHeading = heading;
this.printedValues.put(heading, new HashMap<String, Object>());
}
@Override
public void printValue(String label, Object value) {
Assert.notNull(this.printedHeading,
"Heading not printed before label " + label + " with value " + value);
this.printedValues.get(this.printedHeading).put(label, value);
}
}
}
public void handle() {
}
}

View File

@@ -0,0 +1,82 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.servlet.result;
import static org.junit.Assert.fail;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.springframework.core.Conventions;
import org.springframework.http.HttpStatus;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultMatcher;
import org.springframework.test.web.servlet.StubMvcResult;
import org.springframework.test.web.servlet.result.StatusResultMatchers;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;
/**
* Tests for {@link StatusResultMatchers}.
*
* @author Rossen Stoyanchev
*/
public class StatusResultMatchersTests {
@Test
public void testHttpStatusCodeResultMatchers() throws Exception {
StatusResultMatchers resultMatchers = new StatusResultMatchers();
List<AssertionError> failures = new ArrayList<AssertionError>();
for(HttpStatus status : HttpStatus.values()) {
MockHttpServletResponse response = new MockHttpServletResponse();
response.setStatus(status.value());
String methodName = statusToMethodName(status);
Method method = StatusResultMatchers.class.getMethod(methodName);
try {
ResultMatcher matcher = (ResultMatcher) ReflectionUtils.invokeMethod(method, resultMatchers);
try {
MvcResult mvcResult = new StubMvcResult(new MockHttpServletRequest(), null, null, null, null, null, response);
matcher.match(mvcResult);
}
catch (AssertionError error) {
failures.add(error);
}
}
catch (Exception ex) {
throw new Exception("Failed to obtain ResultMatcher: " + method.toString(), ex);
}
}
if (!failures.isEmpty()) {
fail("Failed status codes: " + failures);
}
}
private String statusToMethodName(HttpStatus status) throws NoSuchMethodException {
String name = status.name().toLowerCase().replace("_", "-");
return "is" + StringUtils.capitalize(Conventions.attributeNameToPropertyName(name));
}
}

View File

@@ -0,0 +1,111 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.servlet.result;
import org.hamcrest.Matchers;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.web.servlet.StubMvcResult;
import org.springframework.test.web.servlet.result.XpathResultMatchers;
/**
* Tests for {@link XpathResultMatchers}.
*
* @author Rossen Stoyanchev
*/
public class XpathResultMatchersTests {
@Test
public void testNodeMatcher() throws Exception {
new XpathResultMatchers("/foo/bar", null).node(Matchers.notNullValue()).match(getStubMvcResult());
}
@Test(expected=AssertionError.class)
public void testNodeMatcherNoMatch() throws Exception {
new XpathResultMatchers("/foo/bar", null).node(Matchers.nullValue()).match(getStubMvcResult());
}
@Test
public void testExists() throws Exception {
new XpathResultMatchers("/foo/bar", null).exists().match(getStubMvcResult());
}
@Test(expected=AssertionError.class)
public void testExistsNoMatch() throws Exception {
new XpathResultMatchers("/foo/Bar", null).exists().match(getStubMvcResult());
}
@Test
public void testDoesNotExist() throws Exception {
new XpathResultMatchers("/foo/Bar", null).doesNotExist().match(getStubMvcResult());
}
@Test(expected=AssertionError.class)
public void testDoesNotExistNoMatch() throws Exception {
new XpathResultMatchers("/foo/bar", null).doesNotExist().match(getStubMvcResult());
}
@Test
public void testNodeCount() throws Exception {
new XpathResultMatchers("/foo/bar", null).nodeCount(2).match(getStubMvcResult());
}
@Test(expected=AssertionError.class)
public void testNodeCountNoMatch() throws Exception {
new XpathResultMatchers("/foo/bar", null).nodeCount(1).match(getStubMvcResult());
}
@Test
public void testString() throws Exception {
new XpathResultMatchers("/foo/bar[1]", null).string("111").match(getStubMvcResult());
}
@Test(expected=AssertionError.class)
public void testStringNoMatch() throws Exception {
new XpathResultMatchers("/foo/bar[1]", null).string("112").match(getStubMvcResult());
}
@Test
public void testNumber() throws Exception {
new XpathResultMatchers("/foo/bar[1]", null).number(111.0).match(getStubMvcResult());
}
@Test(expected=AssertionError.class)
public void testNumberNoMatch() throws Exception {
new XpathResultMatchers("/foo/bar[1]", null).number(111.1).match(getStubMvcResult());
}
@Test
public void testBoolean() throws Exception {
new XpathResultMatchers("/foo/bar[2]", null).booleanValue(true).match(getStubMvcResult());
}
@Test(expected=AssertionError.class)
public void testBooleanNoMatch() throws Exception {
new XpathResultMatchers("/foo/bar[2]", null).booleanValue(false).match(getStubMvcResult());
}
private static final String RESPONSE_CONTENT = "<foo><bar>111</bar><bar>true</bar></foo>";
private StubMvcResult getStubMvcResult() throws Exception {
MockHttpServletResponse response = new MockHttpServletResponse();
response.addHeader("Content-Type", "application/json");
response.getWriter().print(new String(RESPONSE_CONTENT.getBytes("ISO-8859-1")));
return new StubMvcResult(null, null, null, null, null, null, response);
}
}

View File

@@ -0,0 +1,149 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.servlet.samples.context;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.ContextHierarchy;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.Person;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.samples.context.JavaConfigTests.RootConfig;
import org.springframework.test.web.servlet.samples.context.JavaConfigTests.WebConfig;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.UrlBasedViewResolver;
import org.springframework.web.servlet.view.tiles3.TilesConfigurer;
import org.springframework.web.servlet.view.tiles3.TilesView;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.mockito.Mockito.*;
/**
* Tests with Java configuration.
*
* @author Rossen Stoyanchev
* @author Sam Brannen
*/
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration("src/test/resources/META-INF/web-resources")
@ContextHierarchy({
@ContextConfiguration(classes = RootConfig.class),
@ContextConfiguration(classes = WebConfig.class)
})
public class JavaConfigTests {
@Autowired
private WebApplicationContext wac;
@Autowired
private PersonDao personDao;
private MockMvc mockMvc;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
when(this.personDao.getPerson(5L)).thenReturn(new Person("Joe"));
}
@Test
public void person() throws Exception {
this.mockMvc.perform(get("/person/5").accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().string("{\"name\":\"Joe\",\"someDouble\":0.0,\"someBoolean\":false}"));
}
@Test
public void tilesDefinitions() throws Exception {
this.mockMvc.perform(get("/"))//
.andExpect(status().isOk())//
.andExpect(forwardedUrl("/WEB-INF/layouts/standardLayout.jsp"));
}
@Configuration
static class RootConfig {
@Bean
public PersonDao personDao() {
return Mockito.mock(PersonDao.class);
}
}
@Configuration
@EnableWebMvc
static class WebConfig extends WebMvcConfigurerAdapter {
@Autowired
private RootConfig rootConfig;
@Bean
public PersonController personController() {
return new PersonController(this.rootConfig.personDao());
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("home");
}
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
@Bean
public UrlBasedViewResolver urlBasedViewResolver() {
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setViewClass(TilesView.class);
return resolver;
}
@Bean
public TilesConfigurer tilesConfigurer() {
TilesConfigurer configurer = new TilesConfigurer();
configurer.setDefinitions(new String[] {"/WEB-INF/**/tiles.xml"});
return configurer;
}
}
}

View File

@@ -0,0 +1,42 @@
/*
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.servlet.samples.context;
import org.springframework.stereotype.Controller;
import org.springframework.test.web.Person;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class PersonController {
private final PersonDao personDao;
public PersonController(PersonDao personDao) {
this.personDao = personDao;
}
@RequestMapping(value="/person/{id}", method=RequestMethod.GET)
@ResponseBody
public Person getPerson(@PathVariable long id) {
return this.personDao.getPerson(id);
}
}

View File

@@ -0,0 +1,25 @@
/*
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.servlet.samples.context;
import org.springframework.test.web.Person;
public interface PersonDao {
Person getPerson(Long id);
}

View File

@@ -0,0 +1,88 @@
/*
* Copyright 2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.servlet.samples.context;
import static org.hamcrest.Matchers.containsString;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrl;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.handler;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.ContextHierarchy;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler;
/**
* Tests dependent on access to resources under the web application root directory.
*
* @author Rossen Stoyanchev
*/
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration("src/test/resources/META-INF/web-resources")
@ContextHierarchy({
@ContextConfiguration("root-context.xml"),
@ContextConfiguration("servlet-context.xml")
})
public class WebAppResourceTests {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).alwaysExpect(status().isOk()).build();
}
// TilesConfigurer: resources under "/WEB-INF/**/tiles.xml"
@Test
public void tilesDefinitions() throws Exception {
this.mockMvc.perform(get("/"))
.andExpect(forwardedUrl("/WEB-INF/layouts/standardLayout.jsp"));
}
// Resources served via <mvc:resources/>
@Test
public void resourceRequest() throws Exception {
this.mockMvc.perform(get("/resources/Spring.js"))
.andExpect(content().contentType("text/javascript"))
.andExpect(content().string(containsString("Spring={};")));
}
// Forwarded to the "default" servlet via <mvc:default-servlet-handler/>
@Test
public void resourcesViaDefaultServlet() throws Exception {
this.mockMvc.perform(get("/unknown/resource"))
.andExpect(handler().handlerType(DefaultServletHttpRequestHandler.class))
.andExpect(forwardedUrl("default"));
}
}

View File

@@ -0,0 +1,83 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.servlet.samples.context;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.ContextHierarchy;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.Person;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* Tests with XML configuration.
*
* @author Rossen Stoyanchev
* @author Sam Brannen
*/
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration("src/test/resources/META-INF/web-resources")
@ContextHierarchy({
@ContextConfiguration("root-context.xml"),
@ContextConfiguration("servlet-context.xml")
})
public class XmlConfigTests {
@Autowired
private WebApplicationContext wac;
@Autowired
private PersonDao personDao;
private MockMvc mockMvc;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
when(this.personDao.getPerson(5L)).thenReturn(new Person("Joe"));
}
@Test
public void person() throws Exception {
this.mockMvc.perform(get("/person/5").accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().string("{\"name\":\"Joe\",\"someDouble\":0.0,\"someBoolean\":false}"));
}
@Test
public void tilesDefinitions() throws Exception {
this.mockMvc.perform(get("/"))//
.andExpect(status().isOk())//
.andExpect(forwardedUrl("/WEB-INF/layouts/standardLayout.jsp"));
}
}

View File

@@ -0,0 +1,126 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.servlet.samples.standalone;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.request;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;
import java.util.Collection;
import java.util.concurrent.Callable;
import java.util.concurrent.CopyOnWriteArrayList;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.test.web.Person;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.async.DeferredResult;
/**
* Tests with asynchronous request handling.
*
* @author Rossen Stoyanchev
*/
public class AsyncTests {
private MockMvc mockMvc;
private AsyncController asyncController;
@Before
public void setup() {
this.asyncController = new AsyncController();
this.mockMvc = standaloneSetup(this.asyncController).build();
}
@Test
@Ignore
public void testCallable() throws Exception {
MvcResult mvcResult = this.mockMvc.perform(get("/1").param("callable", "true"))
.andDo(print())
.andExpect(request().asyncStarted())
.andExpect(request().asyncResult(new Person("Joe")))
.andReturn();
this.mockMvc.perform(asyncDispatch(mvcResult))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(content().string("{\"name\":\"Joe\",\"someDouble\":0.0,\"someBoolean\":false}"));
}
@Test
@Ignore
public void testDeferredResult() throws Exception {
MvcResult mvcResult = this.mockMvc.perform(get("/1").param("deferredResult", "true"))
.andExpect(request().asyncStarted())
.andReturn();
this.asyncController.onMessage("Joe");
this.mockMvc.perform(asyncDispatch(mvcResult))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(content().string("{\"name\":\"Joe\",\"someDouble\":0.0,\"someBoolean\":false}"));
}
@Controller
private static class AsyncController {
private Collection<DeferredResult<Person>> deferredResults = new CopyOnWriteArrayList<DeferredResult<Person>>();
@RequestMapping(value="/{id}", params="callable", produces="application/json")
@ResponseBody
public Callable<Person> getCallable(final Model model) {
return new Callable<Person>() {
@Override
public Person call() throws Exception {
return new Person("Joe");
}
};
}
@RequestMapping(value="/{id}", params="deferredResult", produces="application/json")
@ResponseBody
public DeferredResult<Person> getDeferredResult() {
DeferredResult<Person> deferredResult = new DeferredResult<Person>();
this.deferredResults.add(deferredResult);
return deferredResult;
}
public void onMessage(String name) {
for (DeferredResult<Person> deferredResult : this.deferredResults) {
deferredResult.setResult(new Person(name));
this.deferredResults.remove(deferredResult);
}
}
}
}

View File

@@ -0,0 +1,63 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.servlet.samples.standalone;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrl;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;
import org.junit.Test;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* Exception handling via {@code @ExceptionHandler} method.
*
* @author Rossen Stoyanchev
*/
public class ExceptionHandlerTests {
@Test
public void testExceptionHandlerMethod() throws Exception {
standaloneSetup(new PersonController()).build()
.perform(get("/person/Clyde"))
.andExpect(status().isOk())
.andExpect(forwardedUrl("errorView"));
}
@Controller
private static class PersonController {
@RequestMapping(value="/person/{name}", method=RequestMethod.GET)
public String show(@PathVariable String name) {
if (name.equals("Clyde")) {
throw new IllegalArgumentException("Black listed");
}
return "person/show";
}
@ExceptionHandler
public String handleException(IllegalArgumentException exception) {
return "errorView";
}
}
}

View File

@@ -0,0 +1,60 @@
/*
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.servlet.samples.standalone;
import java.io.IOException;
import org.junit.Test;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*;
/**
* @author Rossen Stoyanchev
*/
public class FileUploadControllerTests {
@Test
public void readString() throws Exception {
MockMultipartFile file = new MockMultipartFile("file", "orig", null, "bar".getBytes());
standaloneSetup(new FileUploadController()).build()
.perform(fileUpload("/fileupload").file(file))
.andExpect(model().attribute("message", "File 'orig' uploaded successfully"));
}
@Controller
private static class FileUploadController {
@RequestMapping(value="/fileupload", method=RequestMethod.POST)
public String processUpload(@RequestParam MultipartFile file, Model model) throws IOException {
model.addAttribute("message", "File '" + file.getOriginalFilename() + "' uploaded successfully");
return "redirect:/index";
}
}
}

View File

@@ -0,0 +1,172 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package org.springframework.test.web.servlet.samples.standalone;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.flash;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;
import java.io.IOException;
import java.security.Principal;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import javax.validation.Valid;
import org.junit.Test;
import org.springframework.stereotype.Controller;
import org.springframework.test.web.Person;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
/**
* Tests with {@link Filter}'s.
*
* @author Rob Winch
*/
public class FilterTests {
@Test
public void whenFiltersCompleteMvcProcessesRequest() throws Exception {
standaloneSetup(new PersonController())
.addFilters(new ContinueFilter()).build()
.perform(post("/persons").param("name", "Andy"))
.andExpect(status().isMovedTemporarily())
.andExpect(redirectedUrl("/person/1"))
.andExpect(model().size(1))
.andExpect(model().attributeExists("id"))
.andExpect(flash().attributeCount(1))
.andExpect(flash().attribute("message", "success!"));
}
@Test
public void filtersProcessRequest() throws Exception {
standaloneSetup(new PersonController())
.addFilters(new ContinueFilter(), new RedirectFilter()).build()
.perform(post("/persons").param("name", "Andy"))
.andExpect(redirectedUrl("/login"));
}
@Test
public void filterMappedBySuffix() throws Exception {
standaloneSetup(new PersonController())
.addFilter(new RedirectFilter(), "*.html").build()
.perform(post("/persons.html").param("name", "Andy"))
.andExpect(redirectedUrl("/login"));
}
@Test
public void filterWithExactMapping() throws Exception {
standaloneSetup(new PersonController())
.addFilter(new RedirectFilter(), "/p", "/persons").build()
.perform(post("/persons").param("name", "Andy"))
.andExpect(redirectedUrl("/login"));
}
@Test
public void filterSkipped() throws Exception {
standaloneSetup(new PersonController())
.addFilter(new RedirectFilter(), "/p", "/person").build()
.perform(post("/persons").param("name", "Andy"))
.andExpect(status().isMovedTemporarily())
.andExpect(redirectedUrl("/person/1"))
.andExpect(model().size(1))
.andExpect(model().attributeExists("id"))
.andExpect(flash().attributeCount(1))
.andExpect(flash().attribute("message", "success!"));
}
@Test
public void filterWrapsRequestResponse() throws Exception {
standaloneSetup(new PersonController())
.addFilters(new WrappingRequestResponseFilter()).build()
.perform(post("/user"))
.andExpect(model().attribute("principal", WrappingRequestResponseFilter.PRINCIPAL_NAME));
}
@Controller
private static class PersonController {
@RequestMapping(value="/persons", method=RequestMethod.POST)
public String save(@Valid Person person, Errors errors, RedirectAttributes redirectAttrs) {
if (errors.hasErrors()) {
return "person/add";
}
redirectAttrs.addAttribute("id", "1");
redirectAttrs.addFlashAttribute("message", "success!");
return "redirect:/person/{id}";
}
@RequestMapping(value="/user")
public ModelAndView user(Principal principal) {
return new ModelAndView("user/view", "principal", principal.getName());
}
@RequestMapping(value="/forward")
public String forward() {
return "forward:/persons";
}
}
private class ContinueFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
filterChain.doFilter(request, response);
}
}
private static class WrappingRequestResponseFilter extends OncePerRequestFilter {
public static final String PRINCIPAL_NAME = "WrapRequestResponseFilterPrincipal";
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
filterChain.doFilter(new HttpServletRequestWrapper(request) {
@Override
public Principal getUserPrincipal() {
return new Principal() {
@Override
public String getName() {
return PRINCIPAL_NAME;
}
};
}
}, new HttpServletResponseWrapper(response));
}
}
private class RedirectFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
response.sendRedirect("/login");
}
}
}

View File

@@ -0,0 +1,103 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.servlet.samples.standalone;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;
import javax.validation.Valid;
import org.junit.Before;
import org.junit.Test;
import org.springframework.stereotype.Controller;
import org.springframework.test.web.Person;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
/**
* Redirect scenarios including saving and retrieving flash attributes.
*
* @author Rossen Stoyanchev
*/
public class RedirectTests {
private MockMvc mockMvc;
@Before
public void setup() {
this.mockMvc = standaloneSetup(new PersonController()).build();
}
@Test
public void save() throws Exception {
this.mockMvc.perform(post("/persons").param("name", "Andy"))
.andExpect(status().isMovedTemporarily())
.andExpect(redirectedUrl("/persons/Joe"))
.andExpect(model().size(1))
.andExpect(model().attributeExists("name"))
.andExpect(flash().attributeCount(1))
.andExpect(flash().attribute("message", "success!"));
}
@Test
public void saveWithErrors() throws Exception {
this.mockMvc.perform(post("/persons"))
.andExpect(status().isOk())
.andExpect(forwardedUrl("persons/add"))
.andExpect(model().size(1))
.andExpect(model().attributeExists("person"))
.andExpect(flash().attributeCount(0));
}
@Test
public void getPerson() throws Exception {
this.mockMvc.perform(get("/persons/Joe").flashAttr("message", "success!"))
.andExpect(status().isOk())
.andExpect(forwardedUrl("persons/index"))
.andExpect(model().size(2))
.andExpect(model().attribute("person", new Person("Joe")))
.andExpect(model().attribute("message", "success!"))
.andExpect(flash().attributeCount(0));
}
@Controller
private static class PersonController {
@RequestMapping(value="/persons/{name}", method=RequestMethod.GET)
public String getPerson(@PathVariable String name, Model model) {
model.addAttribute(new Person(name));
return "persons/index";
}
@RequestMapping(value="/persons", method=RequestMethod.POST)
public String save(@Valid Person person, Errors errors, RedirectAttributes redirectAttrs) {
if (errors.hasErrors()) {
return "persons/add";
}
redirectAttrs.addAttribute("name", "Joe");
redirectAttrs.addFlashAttribute("message", "success!");
return "redirect:/persons/{name}";
}
}
}

View File

@@ -0,0 +1,111 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.servlet.samples.standalone;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.RequestPostProcessor;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* Demonstrates how to implement and plug in a custom {@link RequestPostProcessor}.
*
* @author Rossen Stoyanchev
*/
public class RequestBuilderTests {
private MockMvc mockMvc;
@Before
public void setup() {
this.mockMvc = standaloneSetup(new SampleController())
.defaultRequest(get("/").accept(MediaType.TEXT_PLAIN))
.alwaysExpect(status().isOk()).build();
}
@Test
public void fooHeader() throws Exception {
this.mockMvc.perform(get("/").with(headers().foo("a=b"))).andExpect(
content().string("Foo"));
}
@Test
public void barHeader() throws Exception {
this.mockMvc.perform(get("/").with(headers().bar("a=b"))).andExpect(
content().string("Bar"));
}
private static HeaderRequestPostProcessor headers() {
return new HeaderRequestPostProcessor();
}
/**
* Implementation of {@code RequestPostProcessor} with additional request
* building methods.
*/
private static class HeaderRequestPostProcessor implements RequestPostProcessor {
private HttpHeaders headers = new HttpHeaders();
public HeaderRequestPostProcessor foo(String value) {
this.headers.add("Foo", value);
return this;
}
public HeaderRequestPostProcessor bar(String value) {
this.headers.add("Bar", value);
return this;
}
@Override
public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) {
for (String headerName : this.headers.keySet()) {
request.addHeader(headerName, this.headers.get(headerName));
}
return request;
}
}
@Controller
@RequestMapping("/")
private static class SampleController {
@RequestMapping(headers = "Foo")
@ResponseBody
public String handleFoo() {
return "Foo";
}
@RequestMapping(headers = "Bar")
@ResponseBody
public String handleBar() {
return "Bar";
}
}
}

View File

@@ -0,0 +1,61 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.servlet.samples.standalone;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;
import org.junit.Test;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.test.web.Person;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* Tests demonstrating the use of request parameters.
*
* @author Rossen Stoyanchev
*/
public class RequestParameterTests {
@Test
public void queryParameter() throws Exception {
standaloneSetup(new PersonController()).build()
.perform(get("/search?name=George").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("George"));
}
@Controller
private class PersonController {
@RequestMapping(value="/search")
@ResponseBody
public Person get(@RequestParam String name) {
Person person = new Person(name);
return person;
}
}
}

View File

@@ -0,0 +1,59 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.servlet.samples.standalone;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;
import org.junit.Test;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.test.web.Person;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* Response written from {@code @ResponseBody} method.
*
* @author Rossen Stoyanchev
*/
public class ResponseBodyTests {
@Test
public void json() throws Exception {
standaloneSetup(new PersonController()).build()
.perform(get("/person/Lee").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.name").value("Lee"));
}
@Controller
private class PersonController {
@RequestMapping(value="/person/{name}")
@ResponseBody
public Person get(@PathVariable String name) {
Person person = new Person(name);
return person;
}
}
}

View File

@@ -0,0 +1,160 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.servlet.samples.standalone;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasProperty;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrl;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.xpath;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.springframework.http.MediaType;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.stereotype.Controller;
import org.springframework.test.web.Person;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.ui.Model;
import org.springframework.web.accept.ContentNegotiationManager;
import org.springframework.web.accept.FixedContentNegotiationStrategy;
import org.springframework.web.accept.HeaderContentNegotiationStrategy;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.view.ContentNegotiatingViewResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.json.MappingJacksonJsonView;
import org.springframework.web.servlet.view.xml.MarshallingView;
/**
* Tests with view resolution.
*
* @author Rossen Stoyanchev
*/
public class ViewResolutionTests {
@Test
public void testJspOnly() throws Exception {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/");
viewResolver.setSuffix(".jsp");
standaloneSetup(new PersonController()).setViewResolvers(viewResolver).build()
.perform(get("/person/Corea"))
.andExpect(status().isOk())
.andExpect(model().size(1))
.andExpect(model().attributeExists("person"))
.andExpect(forwardedUrl("/WEB-INF/person/show.jsp"));
}
@Test
public void testJsonOnly() throws Exception {
standaloneSetup(new PersonController()).setSingleView(new MappingJacksonJsonView()).build()
.perform(get("/person/Corea"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.person.name").value("Corea"));
}
@Test
public void testXmlOnly() throws Exception {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setClassesToBeBound(Person.class);
standaloneSetup(new PersonController()).setSingleView(new MarshallingView(marshaller)).build()
.perform(get("/person/Corea"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_XML))
.andExpect(xpath("/person/name/text()").string(equalTo("Corea")));
}
@Test
public void testContentNegotiation() throws Exception {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setClassesToBeBound(Person.class);
List<View> viewList = new ArrayList<View>();
viewList.add(new MappingJacksonJsonView());
viewList.add(new MarshallingView(marshaller));
ContentNegotiationManager manager = new ContentNegotiationManager(
new HeaderContentNegotiationStrategy(), new FixedContentNegotiationStrategy(MediaType.TEXT_HTML));
ContentNegotiatingViewResolver cnViewResolver = new ContentNegotiatingViewResolver();
cnViewResolver.setDefaultViews(viewList);
cnViewResolver.setContentNegotiationManager(manager);
cnViewResolver.afterPropertiesSet();
MockMvc mockMvc =
standaloneSetup(new PersonController())
.setViewResolvers(cnViewResolver, new InternalResourceViewResolver())
.build();
mockMvc.perform(get("/person/Corea"))
.andExpect(status().isOk())
.andExpect(model().size(1))
.andExpect(model().attributeExists("person"))
.andExpect(forwardedUrl("person/show"));
mockMvc.perform(get("/person/Corea").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.person.name").value("Corea"));
mockMvc.perform(get("/person/Corea").accept(MediaType.APPLICATION_XML))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_XML))
.andExpect(xpath("/person/name/text()").string(equalTo("Corea")));
}
@Test
public void defaultViewResolver() throws Exception {
standaloneSetup(new PersonController()).build()
.perform(get("/person/Corea"))
.andExpect(model().attribute("person", hasProperty("name", equalTo("Corea"))))
.andExpect(status().isOk())
.andExpect(forwardedUrl("person/show")); // InternalResourceViewResolver
}
@Controller
private static class PersonController {
@RequestMapping(value="/person/{name}", method=RequestMethod.GET)
public String show(@PathVariable String name, Model model) {
Person person = new Person(name);
model.addAttribute(person);
return "person/show";
}
}
}

View File

@@ -0,0 +1,49 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.servlet.samples.standalone.resulthandlers;
import org.junit.Test;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* Print debugging information about the executed request and response to System.out.
*
* @author Rossen Stoyanchev
*/
public class PrintingResultHandlerTests {
@Test
public void testPrint() throws Exception {
// Not testing anything, uncomment to see the output
// standaloneSetup(new SimpleController()).build().perform(get("/")).andDo(print());
}
@Controller
private static class SimpleController {
@RequestMapping("/")
@ResponseBody
public String hello() {
return "Hello world";
}
}
}

View File

@@ -0,0 +1,129 @@
/*
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.servlet.samples.standalone.resultmatchers;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;
import java.nio.charset.Charset;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* Examples of defining expectations on the response content, content type, and
* the character encoding.
*
* @author Rossen Stoyanchev
*
* @see JsonPathAssertionTests
* @see XmlContentAssertionTests
* @see XpathAssertionTests
*/
public class ContentAssertionTests {
public static final MediaType TEXT_PLAIN_UTF8 = new MediaType("text", "plain", Charset.forName("UTF-8"));
private MockMvc mockMvc;
@Before
public void setup() {
this.mockMvc = standaloneSetup(new SimpleController()).alwaysExpect(status().isOk()).build();
}
@Test
public void testContentType() throws Exception {
this.mockMvc.perform(get("/handle").accept(MediaType.TEXT_PLAIN))
.andExpect(content().contentType(MediaType.TEXT_PLAIN))
.andExpect(content().contentType("text/plain"));
this.mockMvc.perform(get("/handleUtf8"))
.andExpect(content().contentType(MediaType.valueOf("text/plain;charset=UTF-8")))
.andExpect(content().contentType("text/plain;charset=UTF-8"))
.andExpect(content().contentTypeCompatibleWith("text/plain"))
.andExpect(content().contentTypeCompatibleWith(MediaType.TEXT_PLAIN));
}
@Test
public void testContentAsString() throws Exception {
this.mockMvc.perform(get("/handle").accept(MediaType.TEXT_PLAIN))
.andExpect(content().string("Hello world!"));
this.mockMvc.perform(get("/handleUtf8"))
.andExpect(content().string("\u3053\u3093\u306b\u3061\u306f\u4e16\u754c\uff01"));
// Hamcrest matchers...
this.mockMvc.perform(get("/handle").accept(MediaType.TEXT_PLAIN)).andExpect(content().string(equalTo("Hello world!")));
this.mockMvc.perform(get("/handleUtf8")).andExpect(content().string(equalTo("\u3053\u3093\u306b\u3061\u306f\u4e16\u754c\uff01")));
}
@Test
public void testContentAsBytes() throws Exception {
this.mockMvc.perform(get("/handle").accept(MediaType.TEXT_PLAIN))
.andExpect(content().bytes("Hello world!".getBytes("ISO-8859-1")));
this.mockMvc.perform(get("/handleUtf8"))
.andExpect(content().bytes("\u3053\u3093\u306b\u3061\u306f\u4e16\u754c\uff01".getBytes("UTF-8")));
}
@Test
public void testContentStringMatcher() throws Exception {
this.mockMvc.perform(get("/handle").accept(MediaType.TEXT_PLAIN))
.andExpect(content().string(containsString("world")));
}
@Test
public void testCharacterEncoding() throws Exception {
this.mockMvc.perform(get("/handle").accept(MediaType.TEXT_PLAIN))
.andExpect(content().encoding("ISO-8859-1"))
.andExpect(content().string(containsString("world")));
this.mockMvc.perform(get("/handleUtf8"))
.andExpect(content().encoding("UTF-8"))
.andExpect(content().bytes("\u3053\u3093\u306b\u3061\u306f\u4e16\u754c\uff01".getBytes("UTF-8")));
}
@Controller
private static class SimpleController {
@RequestMapping(value="/handle", produces="text/plain")
@ResponseBody
public String handle() {
return "Hello world!";
}
@RequestMapping(value="/handleUtf8", produces="text/plain;charset=UTF-8")
@ResponseBody
public String handleWithCharset() {
return "\u3053\u3093\u306b\u3061\u306f\u4e16\u754c\uff01"; // "Hello world! (Japanese)
}
}
}

View File

@@ -0,0 +1,114 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.servlet.samples.standalone.resultmatchers;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.startsWith;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.cookie;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;
import org.junit.Before;
import org.junit.Test;
import org.springframework.stereotype.Controller;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
/**
* Examples of expectations on response cookies values.
*
* @author Rossen Stoyanchev
*/
public class CookieAssertionTests {
private static final String COOKIE_NAME = CookieLocaleResolver.DEFAULT_COOKIE_NAME;
private MockMvc mockMvc;
@Before
public void setup() {
CookieLocaleResolver localeResolver = new CookieLocaleResolver();
localeResolver.setCookieDomain("domain");
this.mockMvc = standaloneSetup(new SimpleController())
.addInterceptors(new LocaleChangeInterceptor())
.setLocaleResolver(localeResolver)
.defaultRequest(get("/").param("locale", "en_US"))
.alwaysExpect(status().isOk())
.build();
}
@Test
public void testExists() throws Exception {
this.mockMvc.perform(get("/")).andExpect(cookie().exists(COOKIE_NAME));
}
@Test
public void testNotExists() throws Exception {
this.mockMvc.perform(get("/")).andExpect(cookie().doesNotExist("unknowCookie"));
}
@Test
public void testEqualTo() throws Exception {
this.mockMvc.perform(get("/")).andExpect(cookie().value(COOKIE_NAME, "en_US"));
this.mockMvc.perform(get("/")).andExpect(cookie().value(COOKIE_NAME, equalTo("en_US")));
}
@Test
public void testMatcher() throws Exception {
this.mockMvc.perform(get("/")).andExpect(cookie().value(COOKIE_NAME, startsWith("en")));
}
@Test
public void testMaxAge() throws Exception {
this.mockMvc.perform(get("/")).andExpect(cookie().maxAge(COOKIE_NAME, -1));
}
@Test
public void testDomain() throws Exception {
this.mockMvc.perform(get("/")).andExpect(cookie().domain(COOKIE_NAME, "domain"));
}
@Test
public void testVersion() throws Exception {
this.mockMvc.perform(get("/")).andExpect(cookie().version(COOKIE_NAME, 0));
}
@Test
public void testPath() throws Exception {
this.mockMvc.perform(get("/")).andExpect(cookie().path(COOKIE_NAME, "/"));
}
@Test
public void testSecured() throws Exception {
this.mockMvc.perform(get("/")).andExpect(cookie().secure(COOKIE_NAME, false));
}
@Controller
private static class SimpleController {
@RequestMapping("/")
public String home() {
return "home";
}
}
}

View File

@@ -0,0 +1,93 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.servlet.samples.standalone.resultmatchers;
import static org.hamcrest.Matchers.closeTo;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.flash;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;
import java.net.URL;
import org.junit.Before;
import org.junit.Test;
import org.springframework.stereotype.Controller;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
/**
* Examples of expectations on flash attributes.
*
* @author Rossen Stoyanchev
*/
public class FlashAttributeAssertionTests {
private MockMvc mockMvc;
@Before
public void setup() {
this.mockMvc = standaloneSetup(new PersonController())
.alwaysExpect(status().isMovedTemporarily())
.alwaysExpect(flash().attributeCount(3))
.build();
}
@Test
public void testExists() throws Exception {
this.mockMvc.perform(post("/persons"))
.andExpect(flash().attributeExists("one", "two", "three"));
}
@Test
public void testEqualTo() throws Exception {
this.mockMvc.perform(post("/persons"))
.andExpect(flash().attribute("one", "1"))
.andExpect(flash().attribute("two", 2.222))
.andExpect(flash().attribute("three", new URL("http://example.com")))
.andExpect(flash().attribute("one", equalTo("1"))) // Hamcrest...
.andExpect(flash().attribute("two", equalTo(2.222)))
.andExpect(flash().attribute("three", equalTo(new URL("http://example.com"))));
}
@Test
public void testMatchers() throws Exception {
this.mockMvc.perform(post("/persons"))
.andExpect(flash().attribute("one", containsString("1")))
.andExpect(flash().attribute("two", closeTo(2, 0.5)))
.andExpect(flash().attribute("three", notNullValue()));
}
@Controller
private static class PersonController {
@RequestMapping(value="/persons", method=RequestMethod.POST)
public String save(RedirectAttributes redirectAttrs) throws Exception {
redirectAttrs.addFlashAttribute("one", "1");
redirectAttrs.addFlashAttribute("two", 2.222);
redirectAttrs.addFlashAttribute("three", new URL("http://example.com"));
return "redirect:/person/1";
}
}
}

View File

@@ -0,0 +1,85 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.servlet.samples.standalone.resultmatchers;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.handler;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;
import java.lang.reflect.Method;
import org.junit.Before;
import org.junit.Test;
import org.springframework.stereotype.Controller;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* Examples of expectations on the handler or handler method that executed the request.
*
* <p>Note that in most cases "handler" is synonymous with "controller".
* For example an {@code @Controller} is a kind of handler.
*
* @author Rossen Stoyanchev
*/
public class HandlerAssertionTests {
private MockMvc mockMvc;
@Before
public void setup() {
this.mockMvc = standaloneSetup(new SimpleController()).alwaysExpect(status().isOk()).build();
}
@Test
public void testHandlerType() throws Exception {
this.mockMvc.perform(get("/")).andExpect(handler().handlerType(SimpleController.class));
}
@Test
public void testHandlerMethodNameEqualTo() throws Exception {
this.mockMvc.perform(get("/")).andExpect(handler().methodName("handle"));
// Hamcrest matcher..
this.mockMvc.perform(get("/")).andExpect(handler().methodName(equalTo("handle")));
}
@Test
public void testHandlerMethodNameMatcher() throws Exception {
this.mockMvc.perform(get("/")).andExpect(handler().methodName(is(not("save"))));
}
@Test
public void testHandlerMethod() throws Exception {
Method method = SimpleController.class.getMethod("handle");
this.mockMvc.perform(get("/")).andExpect(handler().method(method));
}
@Controller
private static class SimpleController {
@RequestMapping("/")
public String handle() {
return "view";
}
}
}

View File

@@ -0,0 +1,200 @@
/*
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.servlet.samples.standalone.resultmatchers;
import org.junit.Before;
import org.junit.Test;
import org.springframework.stereotype.Controller;
import org.springframework.test.web.Person;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultMatcher;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*;
/**
* Examples of expectations on response header values.
*
* @author Rossen Stoyanchev
* @author Sam Brannen
*/
public class HeaderAssertionTests {
private static final String EXPECTED_ASSERTION_ERROR_MSG = "Should have thrown an AssertionError";
private static final String IF_MODIFIED_SINCE = "If-Modified-Since";
private static final String LAST_MODIFIED = "Last-Modified";
private final long currentTime = System.currentTimeMillis();
private MockMvc mockMvc;
private PersonController personController;
@Before
public void setup() {
this.personController = new PersonController();
this.personController.setStubTimestamp(currentTime);
this.mockMvc = standaloneSetup(this.personController).build();
}
@Test
public void stringWithCorrectResponseHeaderValue() throws Exception {
this.mockMvc.perform(get("/persons/1").header(IF_MODIFIED_SINCE, currentTime - (1000 * 60)))//
.andExpect(header().string(LAST_MODIFIED, String.valueOf(currentTime)));
}
@Test
public void stringWithMatcherAndCorrectResponseHeaderValue() throws Exception {
this.mockMvc.perform(get("/persons/1").header(IF_MODIFIED_SINCE, currentTime - (1000 * 60)))//
.andExpect(header().string(LAST_MODIFIED, equalTo(String.valueOf(currentTime))));
}
@Test
public void longValueWithCorrectResponseHeaderValue() throws Exception {
this.mockMvc.perform(get("/persons/1").header(IF_MODIFIED_SINCE, currentTime - (1000 * 60)))//
.andExpect(header().longValue(LAST_MODIFIED, currentTime));
}
@Test
public void stringWithMissingResponseHeader() throws Exception {
this.mockMvc.perform(get("/persons/1").header(IF_MODIFIED_SINCE, currentTime))//
.andExpect(status().isNotModified())//
.andExpect(header().string(LAST_MODIFIED, (String) null));
}
@Test
public void stringWithMatcherAndMissingResponseHeader() throws Exception {
this.mockMvc.perform(get("/persons/1").header(IF_MODIFIED_SINCE, currentTime))//
.andExpect(status().isNotModified())//
.andExpect(header().string(LAST_MODIFIED, nullValue()));
}
@Test
public void longValueWithMissingResponseHeader() throws Exception {
try {
this.mockMvc.perform(get("/persons/1").header(IF_MODIFIED_SINCE, currentTime))//
.andExpect(status().isNotModified())//
.andExpect(header().longValue(LAST_MODIFIED, 99L));
fail(EXPECTED_ASSERTION_ERROR_MSG);
}
catch (AssertionError e) {
if (EXPECTED_ASSERTION_ERROR_MSG.equals(e.getMessage())) {
throw e;
}
assertEquals("Response does not contain header " + LAST_MODIFIED, e.getMessage());
}
}
// SPR-10771
@Test
public void doesNotExist() throws Exception {
this.mockMvc.perform(get("/persons/1"))
.andExpect(header().doesNotExist("X-Custom-Header"));
}
// SPR-10771
@Test(expected = AssertionError.class)
public void doesNotExistFail() throws Exception {
this.mockMvc.perform(get("/persons/1"))
.andExpect(header().doesNotExist(LAST_MODIFIED));
}
@Test
public void stringWithIncorrectResponseHeaderValue() throws Exception {
long unexpected = currentTime + 1;
assertIncorrectResponseHeaderValue(header().string(LAST_MODIFIED, String.valueOf(unexpected)), unexpected);
}
@Test
public void stringWithMatcherAndIncorrectResponseHeaderValue() throws Exception {
long unexpected = currentTime + 1;
assertIncorrectResponseHeaderValue(header().string(LAST_MODIFIED, equalTo(String.valueOf(unexpected))),
unexpected);
}
@Test
public void longValueWithIncorrectResponseHeaderValue() throws Exception {
long unexpected = currentTime + 1;
assertIncorrectResponseHeaderValue(header().longValue(LAST_MODIFIED, unexpected), unexpected);
}
private void assertIncorrectResponseHeaderValue(ResultMatcher resultMatcher, long unexpected) throws Exception {
try {
this.mockMvc.perform(get("/persons/1").header(IF_MODIFIED_SINCE, currentTime - (1000 * 60)))//
.andExpect(resultMatcher);
fail(EXPECTED_ASSERTION_ERROR_MSG);
}
catch (AssertionError e) {
if (EXPECTED_ASSERTION_ERROR_MSG.equals(e.getMessage())) {
throw e;
}
// [SPR-10659] Ensure that the header name is included in the message
//
// We don't use assertEquals() since we cannot control the formatting
// produced by JUnit or Hamcrest.
assertMessageContains(e, "Response header " + LAST_MODIFIED);
assertMessageContains(e, String.valueOf(unexpected));
assertMessageContains(e, String.valueOf(currentTime));
}
}
private void assertMessageContains(AssertionError error, String expected) {
String message = error.getMessage();
assertTrue("Failure message should contain: " + expected, message.contains(expected));
}
// -------------------------------------------------------------------------
@Controller
private static class PersonController {
private long timestamp;
public void setStubTimestamp(long timestamp) {
this.timestamp = timestamp;
}
@RequestMapping("/persons/{id}")
@ResponseBody
public Person showEntity(@PathVariable long id, WebRequest request) {
if (request.checkNotModified(calculateLastModified(id))) {
return null;
}
return new Person("Jason");
}
private long calculateLastModified(long id) {
return this.timestamp;
}
}
}

View File

@@ -0,0 +1,146 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.servlet.samples.standalone.resultmatchers;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.isIn;
import static org.hamcrest.Matchers.startsWith;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;
import java.util.Arrays;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.test.web.Person;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* Examples of defining expectations on JSON response content with
* <a href="http://goessner.net/articles/JsonPath/">JSONPath</a> expressions.
*
* @author Rossen Stoyanchev
*
* @see ContentAssertionTests
*/
public class JsonPathAssertionTests {
private MockMvc mockMvc;
@Before
public void setup() {
this.mockMvc = standaloneSetup(new MusicController())
.defaultRequest(get("/").accept(MediaType.APPLICATION_JSON))
.alwaysExpect(status().isOk())
.alwaysExpect(content().contentType("application/json;charset=UTF-8"))
.build();
}
@Test
public void testExists() throws Exception {
String composerByName = "$.composers[?(@.name == '%s')]";
String performerByName = "$.performers[?(@.name == '%s')]";
this.mockMvc.perform(get("/music/people"))
.andExpect(jsonPath(composerByName, "Johann Sebastian Bach").exists())
.andExpect(jsonPath(composerByName, "Johannes Brahms").exists())
.andExpect(jsonPath(composerByName, "Edvard Grieg").exists())
.andExpect(jsonPath(composerByName, "Robert Schumann").exists())
.andExpect(jsonPath(performerByName, "Vladimir Ashkenazy").exists())
.andExpect(jsonPath(performerByName, "Yehudi Menuhin").exists())
.andExpect(jsonPath("$.composers[0]").exists())
.andExpect(jsonPath("$.composers[1]").exists())
.andExpect(jsonPath("$.composers[2]").exists())
.andExpect(jsonPath("$.composers[3]").exists());
}
@Test
public void testDoesNotExist() throws Exception {
this.mockMvc.perform(get("/music/people"))
.andExpect(jsonPath("$.composers[?(@.name == 'Edvard Grieeeeeeg')]").doesNotExist())
.andExpect(jsonPath("$.composers[?(@.name == 'Robert Schuuuuuuman')]").doesNotExist())
.andExpect(jsonPath("$.composers[-1]").doesNotExist())
.andExpect(jsonPath("$.composers[4]").doesNotExist());
}
@Test
public void testEqualTo() throws Exception {
this.mockMvc.perform(get("/music/people"))
.andExpect(jsonPath("$.composers[0].name").value("Johann Sebastian Bach"))
.andExpect(jsonPath("$.performers[1].name").value("Yehudi Menuhin"));
// Hamcrest matchers...
this.mockMvc.perform(get("/music/people"))
.andExpect(jsonPath("$.composers[0].name").value(equalTo("Johann Sebastian Bach")))
.andExpect(jsonPath("$.performers[1].name").value(equalTo("Yehudi Menuhin")));
}
@Test
public void testHamcrestMatcher() throws Exception {
this.mockMvc.perform(get("/music/people"))
.andExpect(jsonPath("$.composers[0].name", startsWith("Johann")))
.andExpect(jsonPath("$.performers[0].name", endsWith("Ashkenazy")))
.andExpect(jsonPath("$.performers[1].name", containsString("di Me")))
.andExpect(jsonPath("$.composers[1].name", isIn(Arrays.asList("Johann Sebastian Bach", "Johannes Brahms"))));
}
@Test
public void testHamcrestMatcherWithParameterizedJsonPath() throws Exception {
String composerName = "$.composers[%s].name";
String performerName = "$.performers[%s].name";
this.mockMvc.perform(get("/music/people"))
.andExpect(jsonPath(composerName, 0).value(startsWith("Johann")))
.andExpect(jsonPath(performerName, 0).value(endsWith("Ashkenazy")))
.andExpect(jsonPath(performerName, 1).value(containsString("di Me")))
.andExpect(jsonPath(composerName, 1).value(isIn(Arrays.asList("Johann Sebastian Bach", "Johannes Brahms"))));
}
@Controller
private class MusicController {
@RequestMapping(value="/music/people")
public @ResponseBody MultiValueMap<String, Person> get() {
MultiValueMap<String, Person> map = new LinkedMultiValueMap<String, Person>();
map.add("composers", new Person("Johann Sebastian Bach"));
map.add("composers", new Person("Johannes Brahms"));
map.add("composers", new Person("Edvard Grieg"));
map.add("composers", new Person("Robert Schumann"));
map.add("performers", new Person("Vladimir Ashkenazy"));
map.add("performers", new Person("Yehudi Menuhin"));
return map;
}
}
}

View File

@@ -0,0 +1,123 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.servlet.samples.standalone.resultmatchers;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasProperty;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.Matchers.startsWith;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;
import javax.validation.Valid;
import org.junit.Before;
import org.junit.Test;
import org.springframework.stereotype.Controller;
import org.springframework.test.web.Person;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* Examples of expectations on the content of the model prepared by the controller.
*
* @author Rossen Stoyanchev
*/
public class ModelAssertionTests {
private MockMvc mockMvc;
@Before
public void setup() {
SampleController controller = new SampleController("a string value", 3, new Person("a name"));
this.mockMvc = standaloneSetup(controller)
.defaultRequest(get("/"))
.alwaysExpect(status().isOk())
.build();
}
@Test
public void testAttributeEqualTo() throws Exception {
mockMvc.perform(get("/"))
.andExpect(model().attribute("integer", 3))
.andExpect(model().attribute("string", "a string value"))
.andExpect(model().attribute("integer", equalTo(3))) // Hamcrest...
.andExpect(model().attribute("string", equalTo("a string value")));
}
@Test
public void testAttributeExists() throws Exception {
mockMvc.perform(get("/"))
.andExpect(model().attributeExists("integer", "string", "person"))
.andExpect(model().attribute("integer", notNullValue())) // Hamcrest...
.andExpect(model().attribute("INTEGER", nullValue()));
}
@Test
public void testAttributeHamcrestMatchers() throws Exception {
mockMvc.perform(get("/"))
.andExpect(model().attribute("integer", equalTo(3)))
.andExpect(model().attribute("string", allOf(startsWith("a string"), endsWith("value"))))
.andExpect(model().attribute("person", hasProperty("name", equalTo("a name"))));
}
@Test
public void testHasErrors() throws Exception {
mockMvc.perform(post("/persons")).andExpect(model().attributeHasErrors("person"));
}
@Test
public void testHasNoErrors() throws Exception {
mockMvc.perform(get("/")).andExpect(model().hasNoErrors());
}
@Controller
private static class SampleController {
private final Object[] values;
public SampleController(Object... values) {
this.values = values;
}
@RequestMapping("/")
public String handle(Model model) {
for (Object value : this.values) {
model.addAttribute(value);
}
return "view";
}
@RequestMapping(value="/persons", method=RequestMethod.POST)
public String create(@Valid Person person, BindingResult result, Model model) {
return "view";
}
}
}

View File

@@ -0,0 +1,77 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.servlet.samples.standalone.resultmatchers;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.request;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.HandlerMapping;
/**
* Examples of expectations on created request attributes.
*
* @author Rossen Stoyanchev
*/
public class RequestAttributeAssertionTests {
private MockMvc mockMvc;
@Before
public void setup() {
this.mockMvc = standaloneSetup(new SimpleController()).build();
}
@Test
public void testRequestAttributeEqualTo() throws Exception {
this.mockMvc.perform(get("/main/1").servletPath("/main"))
.andExpect(request().attribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE, "/{id}"))
.andExpect(request().attribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "/1"))
.andExpect(request().attribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE, equalTo("/{id}")))
.andExpect(request().attribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, equalTo("/1")));
}
@Test
public void testRequestAttributeMatcher() throws Exception {
String producibleMediaTypes = HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE;
this.mockMvc.perform(get("/1"))
.andExpect(request().attribute(producibleMediaTypes, hasItem(MediaType.APPLICATION_JSON)))
.andExpect(request().attribute(producibleMediaTypes, not(hasItem(MediaType.APPLICATION_XML))));
}
@Controller
private static class SimpleController {
@RequestMapping(value="/{id}", produces="application/json")
public String show() {
return "view";
}
}
}

View File

@@ -0,0 +1,83 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.servlet.samples.standalone.resultmatchers;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.request;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;
import java.util.Locale;
import org.junit.Before;
import org.junit.Test;
import org.springframework.stereotype.Controller;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
/**
* Examples of expectations on created session attributes.
*
* @author Rossen Stoyanchev
*/
public class SessionAttributeAssertionTests {
private MockMvc mockMvc;
@Before
public void setup() {
this.mockMvc = standaloneSetup(new SimpleController())
.defaultRequest(get("/"))
.alwaysExpect(status().isOk())
.build();
}
@Test
public void testSessionAttributeEqualTo() throws Exception {
this.mockMvc.perform(get("/"))
.andExpect(request().sessionAttribute("locale", Locale.UK))
.andExpect(request().sessionAttribute("locale", equalTo(Locale.UK)));
}
@Test
public void testSessionAttributeMatcher() throws Exception {
this.mockMvc.perform(get("/"))
.andExpect(request().sessionAttribute("locale", notNullValue()));
}
@Controller
@SessionAttributes("locale")
private static class SimpleController {
@ModelAttribute
public void populate(Model model) {
model.addAttribute("locale", Locale.UK);
}
@RequestMapping("/")
public String handle() {
return "view";
}
}
}

View File

@@ -0,0 +1,98 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.servlet.samples.standalone.resultmatchers;
import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.equalTo;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
* Examples of expectations on the status and the status reason found in the response.
*
* @author Rossen Stoyanchev
*/
public class StatusAssertionTests {
private MockMvc mockMvc;
@Before
public void setup() {
this.mockMvc = standaloneSetup(new StatusController()).build();
}
@Test
public void testStatusInt() throws Exception {
this.mockMvc.perform(get("/created")).andExpect(status().is(201));
this.mockMvc.perform(get("/badRequest")).andExpect(status().is(400));
}
@Test
public void testHttpStatus() throws Exception {
this.mockMvc.perform(get("/created")).andExpect(status().isCreated());
this.mockMvc.perform(get("/badRequest")).andExpect(status().isBadRequest());
}
@Test
public void testMatcher() throws Exception {
this.mockMvc.perform(get("/badRequest")).andExpect(status().is(equalTo(400)));
}
@Test
public void testReasonEqualTo() throws Exception {
this.mockMvc.perform(get("/badRequest")).andExpect(status().reason("Expired token"));
// Hamcrest matchers...
this.mockMvc.perform(get("/badRequest")).andExpect(status().reason(equalTo("Expired token")));
}
@Test
public void testReasonMatcher() throws Exception {
this.mockMvc.perform(get("/badRequest"))
.andExpect(status().reason(endsWith("token")));
}
@Controller
private static class StatusController {
@RequestMapping("/created")
@ResponseStatus(HttpStatus.CREATED)
public @ResponseBody void created(){
}
@RequestMapping("/badRequest")
@ResponseStatus(value=HttpStatus.BAD_REQUEST, reason="Expired token")
public @ResponseBody void badRequest(){
}
@RequestMapping("/notImplemented")
@ResponseStatus(HttpStatus.NOT_IMPLEMENTED)
public @ResponseBody void notImplemented(){
}
}
}

View File

@@ -0,0 +1,79 @@
/*
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.servlet.samples.standalone.resultmatchers;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrl;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrlPattern;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrlPattern;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;
import org.junit.Before;
import org.junit.Test;
import org.springframework.stereotype.Controller;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* Examples of expectations on forwarded or redirected URLs.
*
* @author Rossen Stoyanchev
*/
public class UrlAssertionTests {
private MockMvc mockMvc;
@Before
public void setup() {
this.mockMvc = standaloneSetup(new SimpleController()).build();
}
@Test
public void testRedirect() throws Exception {
this.mockMvc.perform(get("/persons")).andExpect(redirectedUrl("/persons/1"));
}
@Test
public void testRedirectPattern() throws Exception {
this.mockMvc.perform(get("/persons")).andExpect(redirectedUrlPattern("/persons/*"));
}
@Test
public void testForward() throws Exception {
this.mockMvc.perform(get("/")).andExpect(forwardedUrl("/home"));
}
@Test
public void testForwardPattern() throws Exception {
this.mockMvc.perform(get("/")).andExpect(forwardedUrlPattern("/ho?e"));
}
@Controller
private static class SimpleController {
@RequestMapping("/persons")
public String save() {
return "redirect:/persons/1";
}
@RequestMapping("/")
public String forward() {
return "forward:/home";
}
}
}

View File

@@ -0,0 +1,69 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.servlet.samples.standalone.resultmatchers;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;
import org.junit.Before;
import org.junit.Test;
import org.springframework.stereotype.Controller;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* Examples of expectations on the view name selected by the controller.
*
* @author Rossen Stoyanchev
*/
public class ViewNameAssertionTests {
private MockMvc mockMvc;
@Before
public void setup() {
this.mockMvc = standaloneSetup(new SimpleController())
.alwaysExpect(status().isOk())
.build();
}
@Test
public void testEqualTo() throws Exception {
this.mockMvc.perform(get("/"))
.andExpect(view().name("mySpecialView"))
.andExpect(view().name(equalTo("mySpecialView")));
}
@Test
public void testHamcrestMatcher() throws Exception {
this.mockMvc.perform(get("/")).andExpect(view().name(containsString("Special")));
}
@Controller
private static class SimpleController {
@RequestMapping("/")
public String handle() {
return "mySpecialView";
}
}
}

View File

@@ -0,0 +1,123 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.servlet.samples.standalone.resultmatchers;
import static org.hamcrest.Matchers.hasXPath;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;
import java.util.Arrays;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.test.web.Person;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* Examples of defining expectations on XML response content with XMLUnit.
*
* @author Rossen Stoyanchev
*
* @see ContentAssertionTests
* @see XpathAssertionTests
*/
public class XmlContentAssertionTests {
private static final String PEOPLE_XML =
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" +
"<people><composers>" +
"<composer><name>Johann Sebastian Bach</name><someBoolean>false</someBoolean><someDouble>21.0</someDouble></composer>" +
"<composer><name>Johannes Brahms</name><someBoolean>false</someBoolean><someDouble>0.0025</someDouble></composer>" +
"<composer><name>Edvard Grieg</name><someBoolean>false</someBoolean><someDouble>1.6035</someDouble></composer>" +
"<composer><name>Robert Schumann</name><someBoolean>false</someBoolean><someDouble>NaN</someDouble></composer>" +
"</composers></people>";
private MockMvc mockMvc;
@Before
public void setup() {
this.mockMvc = standaloneSetup(new MusicController())
.defaultRequest(get("/").accept(MediaType.APPLICATION_XML))
.alwaysExpect(status().isOk())
.alwaysExpect(content().contentType(MediaType.APPLICATION_XML))
.build();
}
@Test
public void testXmlEqualTo() throws Exception {
this.mockMvc.perform(get("/music/people")).andExpect(content().xml(PEOPLE_XML));
}
@Test
public void testNodeHamcrestMatcher() throws Exception {
this.mockMvc.perform(get("/music/people"))
.andExpect(content().node(hasXPath("/people/composers/composer[1]")));
}
@Controller
private static class MusicController {
@RequestMapping(value="/music/people")
public @ResponseBody PeopleWrapper getPeople() {
List<Person> composers = Arrays.asList(
new Person("Johann Sebastian Bach").setSomeDouble(21),
new Person("Johannes Brahms").setSomeDouble(.0025),
new Person("Edvard Grieg").setSomeDouble(1.6035),
new Person("Robert Schumann").setSomeDouble(Double.NaN));
return new PeopleWrapper(composers);
}
}
@SuppressWarnings("unused")
@XmlRootElement(name="people")
@XmlAccessorType(XmlAccessType.FIELD)
private static class PeopleWrapper {
@XmlElementWrapper(name="composers")
@XmlElement(name="composer")
private List<Person> composers;
public PeopleWrapper() {
}
public PeopleWrapper(List<Person> composers) {
this.composers = composers;
}
public List<Person> getComposers() {
return this.composers;
}
}
}

View File

@@ -0,0 +1,232 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.servlet.samples.standalone.resultmatchers;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.test.web.Person;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import static org.hamcrest.Matchers.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*;
import static org.springframework.web.bind.annotation.RequestMethod.*;
/**
* Examples of expectations on XML response content with XPath expressions.
*
* @author Rossen Stoyanchev
*
* @see ContentAssertionTests
* @see XmlContentAssertionTests
*/
public class XpathAssertionTests {
private static final Map<String, String> musicNamespace =
Collections.singletonMap("ns", "http://example.org/music/people");
private MockMvc mockMvc;
@Before
public void setup() throws Exception {
this.mockMvc = standaloneSetup(new MusicController())
.defaultRequest(get("/").accept(MediaType.APPLICATION_XML))
.alwaysExpect(status().isOk())
.alwaysExpect(content().contentType(MediaType.APPLICATION_XML))
.build();
}
@Test
public void testExists() throws Exception {
String composer = "/ns:people/composers/composer[%s]";
String performer = "/ns:people/performers/performer[%s]";
this.mockMvc.perform(get("/music/people"))
.andExpect(xpath(composer, musicNamespace, 1).exists())
.andExpect(xpath(composer, musicNamespace, 2).exists())
.andExpect(xpath(composer, musicNamespace, 3).exists())
.andExpect(xpath(composer, musicNamespace, 4).exists())
.andExpect(xpath(performer, musicNamespace, 1).exists())
.andExpect(xpath(performer, musicNamespace, 2).exists())
.andExpect(xpath(composer, musicNamespace, 1).node(notNullValue()));
}
@Test
public void testDoesNotExist() throws Exception {
String composer = "/ns:people/composers/composer[%s]";
String performer = "/ns:people/performers/performer[%s]";
this.mockMvc.perform(get("/music/people"))
.andExpect(xpath(composer, musicNamespace, 0).doesNotExist())
.andExpect(xpath(composer, musicNamespace, 5).doesNotExist())
.andExpect(xpath(performer, musicNamespace, 0).doesNotExist())
.andExpect(xpath(performer, musicNamespace, 3).doesNotExist())
.andExpect(xpath(composer, musicNamespace, 0).node(nullValue()));
}
@Test
public void testString() throws Exception {
String composerName = "/ns:people/composers/composer[%s]/name";
String performerName = "/ns:people/performers/performer[%s]/name";
this.mockMvc.perform(get("/music/people"))
.andExpect(xpath(composerName, musicNamespace, 1).string("Johann Sebastian Bach"))
.andExpect(xpath(composerName, musicNamespace, 2).string("Johannes Brahms"))
.andExpect(xpath(composerName, musicNamespace, 3).string("Edvard Grieg"))
.andExpect(xpath(composerName, musicNamespace, 4).string("Robert Schumann"))
.andExpect(xpath(performerName, musicNamespace, 1).string("Vladimir Ashkenazy"))
.andExpect(xpath(performerName, musicNamespace, 2).string("Yehudi Menuhin"))
.andExpect(xpath(composerName, musicNamespace, 1).string(equalTo("Johann Sebastian Bach"))) // Hamcrest..
.andExpect(xpath(composerName, musicNamespace, 1).string(startsWith("Johann")))
.andExpect(xpath(composerName, musicNamespace, 1).string(notNullValue()));
}
@Test
public void testNumber() throws Exception {
String composerDouble = "/ns:people/composers/composer[%s]/someDouble";
this.mockMvc.perform(get("/music/people"))
.andExpect(xpath(composerDouble, musicNamespace, 1).number(21d))
.andExpect(xpath(composerDouble, musicNamespace, 2).number(.0025))
.andExpect(xpath(composerDouble, musicNamespace, 3).number(1.6035))
.andExpect(xpath(composerDouble, musicNamespace, 4).number(Double.NaN))
.andExpect(xpath(composerDouble, musicNamespace, 1).number(equalTo(21d))) // Hamcrest..
.andExpect(xpath(composerDouble, musicNamespace, 3).number(closeTo(1.6, .01)));
}
@Test
public void testBoolean() throws Exception {
String performerBooleanValue = "/ns:people/performers/performer[%s]/someBoolean";
this.mockMvc.perform(get("/music/people"))
.andExpect(xpath(performerBooleanValue, musicNamespace, 1).booleanValue(false))
.andExpect(xpath(performerBooleanValue, musicNamespace, 2).booleanValue(true));
}
@Test
public void testNodeCount() throws Exception {
this.mockMvc.perform(get("/music/people"))
.andExpect(xpath("/ns:people/composers/composer", musicNamespace).nodeCount(4))
.andExpect(xpath("/ns:people/performers/performer", musicNamespace).nodeCount(2))
.andExpect(xpath("/ns:people/composers/composer", musicNamespace).nodeCount(equalTo(4))) // Hamcrest..
.andExpect(xpath("/ns:people/performers/performer", musicNamespace).nodeCount(equalTo(2)));
}
// SPR-10704
@Test
public void testFeedWithLinefeedChars() throws Exception {
// Map<String, String> namespace = Collections.singletonMap("ns", "");
standaloneSetup(new BlogFeedController()).build()
.perform(get("/blog.atom").accept(MediaType.APPLICATION_ATOM_XML))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_ATOM_XML))
.andExpect(xpath("//feed/title").string("Test Feed"))
.andExpect(xpath("//feed/icon").string("http://www.example.com/favicon.ico"));
}
@Controller
private static class MusicController {
@RequestMapping(value="/music/people")
public @ResponseBody PeopleWrapper getPeople() {
List<Person> composers = Arrays.asList(
new Person("Johann Sebastian Bach").setSomeDouble(21),
new Person("Johannes Brahms").setSomeDouble(.0025),
new Person("Edvard Grieg").setSomeDouble(1.6035),
new Person("Robert Schumann").setSomeDouble(Double.NaN));
List<Person> performers = Arrays.asList(
new Person("Vladimir Ashkenazy").setSomeBoolean(false),
new Person("Yehudi Menuhin").setSomeBoolean(true));
return new PeopleWrapper(composers, performers);
}
}
@SuppressWarnings("unused")
@XmlRootElement(name="people", namespace="http://example.org/music/people")
@XmlAccessorType(XmlAccessType.FIELD)
private static class PeopleWrapper {
@XmlElementWrapper(name="composers")
@XmlElement(name="composer")
private List<Person> composers;
@XmlElementWrapper(name="performers")
@XmlElement(name="performer")
private List<Person> performers;
public PeopleWrapper() {
}
public PeopleWrapper(List<Person> composers, List<Person> performers) {
this.composers = composers;
this.performers = performers;
}
public List<Person> getComposers() {
return this.composers;
}
public List<Person> getPerformers() {
return this.performers;
}
}
@Controller
public class BlogFeedController {
@RequestMapping(value="/blog.atom", method = { GET, HEAD })
@ResponseBody
public String listPublishedPosts() {
return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n"
+ "<feed xmlns=\"http://www.w3.org/2005/Atom\">\r\n"
+ " <title>Test Feed</title>\r\n"
+ " <icon>http://www.example.com/favicon.ico</icon>\r\n"
+ "</feed>\r\n\r\n";
}
}
}

View File

@@ -0,0 +1,274 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package org.springframework.test.web.servlet.setup;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.springframework.test.util.MatcherAssertionErrors.assertThat;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.web.MockFilterChain;
import org.springframework.mock.web.MockFilterConfig;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
/**
*
* @author Rob Winch
*/
public class ConditionalDelegatingFilterProxyTests {
private MockHttpServletRequest request;
private MockHttpServletResponse response;
private MockFilterChain filterChain;
private MockFilter delegate;
private PatternMappingFilterProxy filter;
@Before
public void setup() {
request = new MockHttpServletRequest();
request.setContextPath("/context");
response = new MockHttpServletResponse();
filterChain = new MockFilterChain();
delegate = new MockFilter();
}
@Test
public void init() throws Exception {
FilterConfig config = new MockFilterConfig();
filter = new PatternMappingFilterProxy(delegate, "/");
filter.init(config);
assertThat(delegate.filterConfig, is(config));
}
@Test
public void destroy() throws Exception {
filter = new PatternMappingFilterProxy(delegate, "/");
filter.destroy();
assertThat(delegate.destroy, is(true));
}
@Test
public void matchExact() throws Exception {
assertFilterInvoked("/test", "/test");
}
@Test
public void matchExactEmpty() throws Exception {
assertFilterInvoked("", "");
}
@Test
public void matchPathMappingAllFolder() throws Exception {
assertFilterInvoked("/test/this", "/*");
}
@Test
public void matchPathMappingAll() throws Exception {
assertFilterInvoked("/test", "/*");
}
@Test
public void matchPathMappingAllContextRoot() throws Exception {
assertFilterInvoked("", "/*");
}
@Test
public void matchPathMappingContextRootAndSlash() throws Exception {
assertFilterInvoked("/", "/*");
}
@Test
public void matchPathMappingFolderPatternWithMultiFolderPath() throws Exception {
assertFilterInvoked("/test/this/here", "/test/*");
}
@Test
public void matchPathMappingFolderPattern() throws Exception {
assertFilterInvoked("/test/this", "/test/*");
}
@Test
public void matchPathMappingNoSuffix() throws Exception {
assertFilterInvoked("/test/", "/test/*");
}
@Test
public void matchPathMappingMissingSlash() throws Exception {
assertFilterInvoked("/test", "/test/*");
}
@Test
public void noMatchPathMappingMulti() throws Exception {
assertFilterNotInvoked("/this/test/here", "/test/*");
}
@Test
public void noMatchPathMappingEnd() throws Exception {
assertFilterNotInvoked("/this/test", "/test/*");
}
@Test
public void noMatchPathMappingEndSuffix() throws Exception {
assertFilterNotInvoked("/test2/", "/test/*");
}
@Test
public void noMatchPathMappingMissingSlash() throws Exception {
assertFilterNotInvoked("/test2", "/test/*");
}
@Test
public void matchExtensionMulti() throws Exception {
assertFilterInvoked("/test/this/here.html", "*.html");
}
@Test
public void matchExtension() throws Exception {
assertFilterInvoked("/test/this.html", "*.html");
}
@Test
public void matchExtensionNoPrefix() throws Exception {
assertFilterInvoked("/.html", "*.html");
}
@Test
public void matchExtensionNoFolder() throws Exception {
assertFilterInvoked("/test.html", "*.html");
}
@Test
public void noMatchExtensionNoSlash() throws Exception {
assertFilterNotInvoked(".html", "*.html");
}
@Test
public void noMatchExtensionSlashEnd() throws Exception {
assertFilterNotInvoked("/index.html/", "*.html");
}
@Test
public void noMatchExtensionPeriodEnd() throws Exception {
assertFilterNotInvoked("/index.html.", "*.html");
}
@Test
public void noMatchExtensionLarger() throws Exception {
assertFilterNotInvoked("/index.htm", "*.html");
}
@Test
public void noMatchInvalidPattern() throws Exception {
// pattern uses extension mapping but starts with / (treated as exact match)
assertFilterNotInvoked("/index.html", "/*.html");
}
/*
* Below are tests from Table 12-1 of the Servlet Specification
*/
@Test
public void specPathMappingMultiFolderPattern() throws Exception {
assertFilterInvoked("/foo/bar/index.html", "/foo/bar/*");
}
@Test
public void specPathMappingMultiFolderPatternAlternate() throws Exception {
assertFilterInvoked("/foo/bar/index.bop", "/foo/bar/*");
}
@Test
public void specPathMappingNoSlash() throws Exception {
assertFilterInvoked("/baz", "/baz/*");
}
@Test
public void specPathMapping() throws Exception {
assertFilterInvoked("/baz/index.html", "/baz/*");
}
@Test
public void specExactMatch() throws Exception {
assertFilterInvoked("/catalog", "/catalog");
}
@Test
public void specExtensionMappingSingleFolder() throws Exception {
assertFilterInvoked("/catalog/racecar.bop", "*.bop");
}
@Test
public void specExtensionMapping() throws Exception {
assertFilterInvoked("/index.bop", "*.bop");
}
private void assertFilterNotInvoked(String requestUri, String pattern) throws Exception {
request.setRequestURI(request.getContextPath() + requestUri);
filter = new PatternMappingFilterProxy(delegate, pattern);
filter.doFilter(request, response, filterChain);
assertThat(delegate.request, equalTo((ServletRequest) null));
assertThat(delegate.response, equalTo((ServletResponse) null));
assertThat(delegate.chain, equalTo((FilterChain) null));
assertThat(filterChain.getRequest(), equalTo((ServletRequest) request));
assertThat(filterChain.getResponse(), equalTo((ServletResponse) response));
filterChain = new MockFilterChain();
}
private void assertFilterInvoked(String requestUri, String pattern) throws Exception {
request.setRequestURI(request.getContextPath() + requestUri);
filter = new PatternMappingFilterProxy(delegate, pattern);
filter.doFilter(request, response, filterChain);
assertThat(delegate.request, equalTo((ServletRequest) request));
assertThat(delegate.response, equalTo((ServletResponse) response));
assertThat(delegate.chain, equalTo((FilterChain) filterChain));
delegate = new MockFilter();
}
private static class MockFilter implements Filter {
private FilterConfig filterConfig;
private ServletRequest request;
private ServletResponse response;
private FilterChain chain;
private boolean destroy;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
ServletException {
this.request = request;
this.response = response;
this.chain = chain;
}
@Override
public void destroy() {
this.destroy = true;
}
}
}

View File

@@ -0,0 +1,82 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package org.springframework.test.web.servlet.setup;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.junit.Before;
import org.junit.Test;
import org.springframework.stereotype.Controller;
import org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.filter.OncePerRequestFilter;
/**
* Tests for {@link DefaultMockMvcBuilder}.
*
* @author Rob Winch
*/
public class DefaultMockMvcBuilderTests {
private DefaultMockMvcBuilder<?> builder;
@Before
public void setup() {
builder = MockMvcBuilders.standaloneSetup(new PersonController());
}
@Test(expected = IllegalArgumentException.class)
public void addFiltersFiltersNull() {
builder.addFilters((Filter[]) null);
}
@Test(expected = IllegalArgumentException.class)
public void addFiltersFiltersContainsNull() {
builder.addFilters(new ContinueFilter(), (Filter) null);
}
@Test(expected = IllegalArgumentException.class)
public void addFilterPatternsNull() {
builder.addFilter(new ContinueFilter(), (String[]) null);
}
@Test(expected = IllegalArgumentException.class)
public void addFilterPatternContainsNull() {
builder.addFilter(new ContinueFilter(), (String) null);
}
@Controller
private static class PersonController {
@RequestMapping(value="/forward")
public String forward() {
return "forward:/persons";
}
}
private class ContinueFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
filterChain.doFilter(request, response);
}
}
}

View File

@@ -0,0 +1,43 @@
package org.springframework.test.web.servlet.setup;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* Test for SPR-10277 (Multiple method chaining when building MockMvc).
*
* @author Wesley Hall
*/
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration
public class Spr10277Tests {
@Autowired
private WebApplicationContext wac;
@Test
public void chainMultiple() {
MockMvcBuilders
.webAppContextSetup(wac)
.addFilter(new CharacterEncodingFilter() )
.defaultRequest(get("/").contextPath("/mywebapp"))
.build();
}
@Configuration
@EnableWebMvc
static class WebConfig extends WebMvcConfigurerAdapter {
}
}

View File

@@ -0,0 +1,64 @@
/*
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.servlet.setup;
import org.junit.Test;
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.mock.web.test.MockServletContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import static org.junit.Assert.*;
/**
* @author Rossen Stoyanchev
*/
public class StandaloneMockMvcBuilderTests {
// SPR-10825
@Test
public void placeHoldersInRequestMapping() throws Exception {
StubWebApplicationContext cxt = new StubWebApplicationContext(new MockServletContext());
StandaloneMockMvcBuilder builder = new StandaloneMockMvcBuilder(new PlaceholderController());
builder.addPlaceHolderValue("sys.login.ajax", "/foo");
builder.initWebAppContext(cxt);
RequestMappingHandlerMapping hm = cxt.getBean(RequestMappingHandlerMapping.class);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo");
HandlerExecutionChain chain = hm.getHandler(request);
assertNotNull(chain);
assertEquals("handleWithPlaceholders", ((HandlerMethod) chain.getHandler()).getMethod().getName());
}
@Controller
private static class PlaceholderController {
@RequestMapping(value = "${sys.login.ajax}")
private void handleWithPlaceholders() { }
}
}