Introduce support for HtmlUnit in Spring MVC Test

This commit introduces integration between MockMvc and HtmlUnit, thus
simplifying end-to-end testing when using HTML-based views and enabling
developers to do the following.

 - Easily test HTML pages using tools such as HtmlUnit, WebDriver, & Geb
   without the need to deploy to a Servlet container

 - Test JavaScript within pages

 - Optionally test using mock services to speed up testing

 - Share logic between in-container, end-to-end tests and
   out-of-container integration tests

Issue: SPR-13158
This commit is contained in:
Rob Winch
2015-06-23 11:31:48 -05:00
committed by Sam Brannen
parent c5a037a5cf
commit b73e39423c
28 changed files with 4123 additions and 0 deletions

View File

@@ -0,0 +1,137 @@
/*
* Copyright 2002-2015 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.htmlunit;
import java.net.URL;
import java.util.Collections;
import com.gargoylesoftware.htmlunit.HttpWebConnection;
import com.gargoylesoftware.htmlunit.Page;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebConnection;
import com.gargoylesoftware.htmlunit.WebRequest;
import com.gargoylesoftware.htmlunit.WebResponse;
import com.gargoylesoftware.htmlunit.WebResponseData;
import com.gargoylesoftware.htmlunit.util.NameValuePair;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.sameInstance;
import static org.hamcrest.Matchers.isEmptyString;
import static org.hamcrest.core.IsNot.not;
import static org.junit.Assert.assertThat;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import static org.mockito.Mockito.*;
import org.mockito.runners.MockitoJUnitRunner;
import static org.springframework.test.web.servlet.htmlunit.DelegatingWebConnection.DelegateWebConnection;
import org.springframework.stereotype.Controller;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
/**
* @author Rob Winch
*/
@RunWith(MockitoJUnitRunner.class)
public class DelegatingWebConnectionTests {
private DelegatingWebConnection webConnection;
@Mock
private WebRequestMatcher matcher1;
@Mock
private WebRequestMatcher matcher2;
@Mock
private WebConnection defaultConnection;
@Mock
private WebConnection connection1;
@Mock
private WebConnection connection2;
private WebRequest request;
private WebResponse expectedResponse;
@Before
public void setUp() throws Exception {
request = new WebRequest(new URL("http://localhost/"));
WebResponseData data = new WebResponseData("".getBytes("UTF-8"),200, "", Collections.<NameValuePair>emptyList());
expectedResponse = new WebResponse(data, request, 100L);
webConnection = new DelegatingWebConnection(defaultConnection, new DelegateWebConnection(matcher1,connection1), new DelegateWebConnection(matcher2,connection2));
}
@Test
public void getResponseDefault() throws Exception {
when(defaultConnection.getResponse(request)).thenReturn(expectedResponse);
WebResponse response = webConnection.getResponse(request);
assertThat(response, sameInstance(expectedResponse));
verify(matcher1).matches(request);
verify(matcher2).matches(request);
verifyNoMoreInteractions(connection1,connection2);
verify(defaultConnection).getResponse(request);
}
@Test
public void getResponseAllMatches() throws Exception {
when(matcher1.matches(request)).thenReturn(true);
when(matcher2.matches(request)).thenReturn(true);
when(connection1.getResponse(request)).thenReturn(expectedResponse);
WebResponse response = webConnection.getResponse(request);
assertThat(response, sameInstance(expectedResponse));
verify(matcher1).matches(request);
verifyNoMoreInteractions(matcher2,connection2,defaultConnection);
verify(connection1).getResponse(request);
}
@Test
public void getResponseSecondMatches() throws Exception {
when(matcher2.matches(request)).thenReturn(true);
when(connection2.getResponse(request)).thenReturn(expectedResponse);
WebResponse response = webConnection.getResponse(request);
assertThat(response, sameInstance(expectedResponse));
verify(matcher1).matches(request);
verify(matcher2).matches(request);
verifyNoMoreInteractions(connection1,defaultConnection);
verify(connection2).getResponse(request);
}
@Test
public void classlevelJavadoc() throws Exception {
WebClient webClient = new WebClient();
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(TestController.class).build();
MockMvcWebConnection mockConnection = new MockMvcWebConnection(mockMvc);
mockConnection.setWebClient(webClient);
WebRequestMatcher cdnMatcher = new UrlRegexRequestMatcher(".*?//code.jquery.com/.*");
WebConnection httpConnection = new HttpWebConnection(webClient);
WebConnection webConnection = new DelegatingWebConnection(mockConnection, new DelegateWebConnection(cdnMatcher, httpConnection));
webClient.setWebConnection(webConnection);
Page page = webClient.getPage("http://code.jquery.com/jquery-1.11.0.min.js");
assertThat(page.getWebResponse().getStatusCode(), equalTo(200));
assertThat(page.getWebResponse().getContentAsString(), not(isEmptyString()));
}
@Controller
static class TestController {}
}

View File

@@ -0,0 +1,31 @@
/*
* Copyright 2002-2015 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.htmlunit;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @author Rob Winch
*/
@Controller
public class ForwardController {
@RequestMapping("/forward")
public String forward() {
return "forward:/";
}
}

View File

@@ -0,0 +1,34 @@
/*
* Copyright 2002-2015 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.htmlunit;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @author Rob Winch
*/
@Controller
public class HelloController {
@RequestMapping
@ResponseBody
public String header(HttpServletRequest request) {
return "hello";
}
}

View File

@@ -0,0 +1,79 @@
/*
* Copyright 2002-2015 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.htmlunit;
import java.net.URL;
import com.gargoylesoftware.htmlunit.WebRequest;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.Test;
import org.springframework.test.web.servlet.htmlunit.HostRequestMatcher;
import org.springframework.test.web.servlet.htmlunit.WebRequestMatcher;
/**
* @author Rob Winch
*/
public class HostRequestMatcherTests {
@Test
public void localhostMatches() throws Exception {
WebRequestMatcher matcher = new HostRequestMatcher("localhost");
boolean matches = matcher.matches(new WebRequest(new URL("http://localhost/jquery-1.11.0.min.js")));
assertThat(matches, equalTo(true));;
matches = matcher.matches(new WebRequest(new URL("http://example.com/jquery-1.11.0.min.js")));
assertThat(matches, equalTo(false));;
}
@Test
public void multipleHosts() throws Exception {
WebRequestMatcher matcher = new HostRequestMatcher("localhost","example.com");
boolean matches = matcher.matches(new WebRequest(new URL("http://localhost/jquery-1.11.0.min.js")));
assertThat(matches, equalTo(true));;
matches = matcher.matches(new WebRequest(new URL("http://example.com/jquery-1.11.0.min.js")));
assertThat(matches, equalTo(true));;
}
@Test
public void specificPort() throws Exception {
WebRequestMatcher matcher = new HostRequestMatcher("localhost:8080");
boolean matches = matcher.matches(new WebRequest(new URL("http://localhost:8080/jquery-1.11.0.min.js")));
assertThat(matches, equalTo(true));;
matches = matcher.matches(new WebRequest(new URL("http://localhost:9090/jquery-1.11.0.min.js")));
assertThat(matches, equalTo(false));;
}
@Test
public void defaultPortInMatcher() throws Exception {
WebRequestMatcher matcher = new HostRequestMatcher("localhost:80");
boolean matches = matcher.matches(new WebRequest(new URL("http://localhost:80/jquery-1.11.0.min.js")));
assertThat(matches, equalTo(true));;
matches = matcher.matches(new WebRequest(new URL("http://localhost/jquery-1.11.0.min.js")));
assertThat(matches, equalTo(true));;
matches = matcher.matches(new WebRequest(new URL("http://localhost:9090/jquery-1.11.0.min.js")));
assertThat(matches, equalTo(false));;
}
}

View File

@@ -0,0 +1,782 @@
/*
* Copyright 2002-2015 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.htmlunit;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
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 javax.servlet.http.HttpSession;
import com.gargoylesoftware.htmlunit.CookieManager;
import com.gargoylesoftware.htmlunit.HttpMethod;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebRequest;
import com.gargoylesoftware.htmlunit.util.NameValuePair;
import org.apache.commons.io.IOUtils;
import org.apache.http.auth.UsernamePasswordCredentials;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
import org.junit.Before;
import org.junit.Test;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.mock.web.MockServletContext;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
/**
*
* @author Rob Winch
*
*/
public class HtmlUnitRequestBuilderTests {
private WebRequest webRequest;
private ServletContext servletContext;
private Map<String, MockHttpSession> sessions;
private WebClient webClient;
private HtmlUnitRequestBuilder requestBuilder;
@Before
public void setUp() throws Exception {
sessions = new HashMap<>();
webRequest = new WebRequest(new URL("http://example.com:80/test/this/here"));
webRequest.setHttpMethod(HttpMethod.GET);
webRequest.setRequestParameters(new ArrayList<>());
webClient = new WebClient();
requestBuilder = new HtmlUnitRequestBuilder(sessions, webClient, webRequest);
servletContext = new MockServletContext();
}
// --- constructor
@Test(expected = IllegalArgumentException.class)
public void constructorNullSessions() {
new HtmlUnitRequestBuilder(null, webClient, webRequest);
}
@Test(expected = IllegalArgumentException.class)
public void constructorNullWebClient() {
new HtmlUnitRequestBuilder(sessions, null, webRequest);
}
@Test(expected = IllegalArgumentException.class)
public void constructorNullWebRequest() {
new HtmlUnitRequestBuilder(sessions, webClient, null);
}
// --- buildRequest
@Test
public void buildRequestBasicAuth() {
String base64Credentials = "dXNlcm5hbWU6cGFzc3dvcmQ=";
String authzHeaderValue = "Basic: " + base64Credentials;
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(base64Credentials);
webRequest.setCredentials(credentials);
webRequest.setAdditionalHeader("Authorization", authzHeaderValue);
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getAuthType(), equalTo("Basic"));
assertThat(actualRequest.getHeader("Authorization"), equalTo(authzHeaderValue));
}
@Test
public void buildRequestCharacterEncoding() {
String charset = "UTF-8";
webRequest.setCharset(charset);
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getCharacterEncoding(), equalTo(charset));
}
@Test
public void buildRequestDefaultCharacterEncoding() {
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getCharacterEncoding(), equalTo("ISO-8859-1"));
}
@Test
public void buildRequestContentLength() {
String content = "some content that has length";
webRequest.setHttpMethod(HttpMethod.POST);
webRequest.setRequestBody(content);
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getContentLength(), equalTo(content.length()));
}
@Test
public void buildRequestContentType() {
String contentType = "text/html;charset=UTF-8";
webRequest.setAdditionalHeader("Content-Type", contentType);
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getContentType(), equalTo(contentType));
assertThat(actualRequest.getHeader("Content-Type"), equalTo(contentType));
}
@Test
public void buildRequestContextPathUsesFirstSegmentByDefault() {
String contextPath = requestBuilder.buildRequest(servletContext).getContextPath();
assertThat(contextPath, equalTo("/test"));
}
@Test
public void buildRequestContextPathUsesNoFirstSegmentWithDefault() throws MalformedURLException {
webRequest.setUrl(new URL("http://example.com/"));
String contextPath = requestBuilder.buildRequest(servletContext).getContextPath();
assertThat(contextPath, equalTo(""));
}
@Test(expected = IllegalArgumentException.class)
public void buildRequestContextPathInvalid() {
requestBuilder.setContextPath("/invalid");
requestBuilder.buildRequest(servletContext).getContextPath();
}
@Test
public void buildRequestContextPathEmpty() {
String expected = "";
requestBuilder.setContextPath(expected);
String contextPath = requestBuilder.buildRequest(servletContext).getContextPath();
assertThat(contextPath, equalTo(expected));
}
@Test
public void buildRequestContextPathExplicit() {
String expected = "/test";
requestBuilder.setContextPath(expected);
String contextPath = requestBuilder.buildRequest(servletContext).getContextPath();
assertThat(contextPath, equalTo(expected));
}
@Test
public void buildRequestContextPathMulti() {
String expected = "/test/this";
requestBuilder.setContextPath(expected);
String contextPath = requestBuilder.buildRequest(servletContext).getContextPath();
assertThat(contextPath, equalTo(expected));
}
@Test
public void buildRequestCookiesNull() {
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getCookies(), nullValue());
}
@Test
public void buildRequestCookiesSingle() {
webRequest.setAdditionalHeader("Cookie", "name=value");
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
Cookie[] cookies = actualRequest.getCookies();
assertThat(cookies.length, equalTo(1));
assertThat(cookies[0].getName(), equalTo("name"));
assertThat(cookies[0].getValue(), equalTo("value"));
}
@Test
public void buildRequestCookiesMulti() {
webRequest.setAdditionalHeader("Cookie", "name=value; name2=value2");
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
Cookie[] cookies = actualRequest.getCookies();
assertThat(cookies.length, equalTo(2));
Cookie cookie = cookies[0];
assertThat(cookie.getName(), equalTo("name"));
assertThat(cookie.getValue(), equalTo("value"));
cookie = cookies[1];
assertThat(cookie.getName(), equalTo("name2"));
assertThat(cookie.getValue(), equalTo("value2"));
}
@Test
public void buildRequestInputStream() throws Exception {
String content = "some content that has length";
webRequest.setHttpMethod(HttpMethod.POST);
webRequest.setRequestBody(content);
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(IOUtils.toString(actualRequest.getInputStream()), equalTo(content));
}
@Test
public void buildRequestLocalAddr() {
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getLocalAddr(), equalTo("127.0.0.1"));
}
@Test
public void buildRequestLocaleDefault() {
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getLocale(), equalTo(Locale.getDefault()));
}
@Test
public void buildRequestLocaleDa() {
webRequest.setAdditionalHeader("Accept-Language", "da");
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getLocale(), equalTo(new Locale("da")));
}
@Test
public void buildRequestLocaleEnGbQ08() {
webRequest.setAdditionalHeader("Accept-Language", "en-gb;q=0.8");
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getLocale(), equalTo(new Locale("en", "gb", "0.8")));
}
@Test
public void buildRequestLocaleEnQ07() {
webRequest.setAdditionalHeader("Accept-Language", "en;q=0.7");
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getLocale(), equalTo(new Locale("en", "", "0.7")));
}
@Test
public void buildRequestLocaleEnUs() {
webRequest.setAdditionalHeader("Accept-Language", "en-US");
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getLocale(), equalTo(Locale.US));
}
@Test
public void buildRequestLocaleFr() {
webRequest.setAdditionalHeader("Accept-Language", "fr");
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getLocale(), equalTo(Locale.FRENCH));
}
@Test
public void buildRequestLocaleMulti() {
webRequest.setAdditionalHeader("Accept-Language", "da, en-gb;q=0.8, en;q=0.7");
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
// FIXME Locale.ENGLISH is due to fact cannot remove it from MockHttpServletRequest
List<Locale> expected = Arrays.asList(new Locale("da"), new Locale("en", "gb", "0.8"), new Locale("en", "",
"0.7"), Locale.ENGLISH);
assertThat(Collections.list(actualRequest.getLocales()), equalTo(expected));
}
@Test
public void buildRequestLocaleName() {
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getLocalName(), equalTo("localhost"));
}
@Test
public void buildRequestLocalPort() {
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getLocalPort(), equalTo(80));
}
@Test
public void buildRequestLocalMissing() throws Exception {
webRequest.setUrl(new URL("http://localhost/test/this"));
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getLocalPort(), equalTo(-1));
}
@Test
public void buildRequestMethods() {
HttpMethod[] methods = HttpMethod.values();
for (HttpMethod expectedMethod : methods) {
webRequest.setHttpMethod(expectedMethod);
String actualMethod = requestBuilder.buildRequest(servletContext).getMethod();
assertThat(actualMethod, equalTo(actualMethod));
}
}
@Test
public void buildRequestParameterMap() throws Exception {
setParameter("name", "value");
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getParameterMap().size(), equalTo(1));
assertThat(actualRequest.getParameter("name"), equalTo("value"));
}
@Test
public void buildRequestParameterMapQuery() throws Exception {
webRequest.setUrl(new URL("http://example.com/example/?name=value"));
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getParameterMap().size(), equalTo(1));
assertThat(actualRequest.getParameter("name"), equalTo("value"));
}
@Test
public void buildRequestParameterMapQueryMulti() throws Exception {
webRequest.setUrl(new URL("http://example.com/example/?name=value&param2=value+2"));
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getParameterMap().size(), equalTo(2));
assertThat(actualRequest.getParameter("name"), equalTo("value"));
assertThat(actualRequest.getParameter("param2"), equalTo("value 2"));
}
@Test
public void buildRequestPathInfo() throws Exception {
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getPathInfo(), nullValue());
}
@Test
public void buildRequestPathInfoNull() throws Exception {
webRequest.setUrl(new URL("http://example.com/example"));
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getPathInfo(), nullValue());
}
@Test
public void buildRequestAndAntPathRequestMatcher() throws Exception {
webRequest.setUrl(new URL("http://example.com/app/login/authenticate"));
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
// verify it is going to work with Spring Security's AntPathRequestMatcher
assertThat(actualRequest.getPathInfo(), nullValue());
assertThat(actualRequest.getServletPath(), equalTo("/login/authenticate"));
}
@Test
public void buildRequestProtocol() throws Exception {
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getProtocol(), equalTo("HTTP/1.1"));
}
@Test
public void buildRequestQuery() throws Exception {
String expectedQuery = "aparam=avalue";
webRequest.setUrl(new URL("http://example.com/example?" + expectedQuery));
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getQueryString(), equalTo(expectedQuery));
}
@Test
public void buildRequestReader() throws Exception {
String expectedBody = "request body";
webRequest.setHttpMethod(HttpMethod.POST);
webRequest.setRequestBody(expectedBody);
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(IOUtils.toString(actualRequest.getReader()), equalTo(expectedBody));
}
@Test
public void buildRequestRemoteAddr() throws Exception {
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getRemoteAddr(), equalTo("127.0.0.1"));
}
@Test
public void buildRequestRemoteHost() throws Exception {
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getRemoteAddr(), equalTo("127.0.0.1"));
}
@Test
public void buildRequestRemotePort() throws Exception {
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getRemotePort(), equalTo(80));
}
@Test
public void buildRequestRemotePort8080() throws Exception {
webRequest.setUrl(new URL("http://example.com:8080/"));
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getRemotePort(), equalTo(8080));
}
@Test
public void buildRequestRemotePort80WithDefault() throws Exception {
webRequest.setUrl(new URL("http://example.com/"));
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getRemotePort(), equalTo(80));
}
@Test
public void buildRequestRequestedSessionId() throws Exception {
String sessionId = "session-id";
webRequest.setAdditionalHeader("Cookie", "JSESSIONID=" + sessionId);
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getRequestedSessionId(), equalTo(sessionId));
}
@Test
public void buildRequestRequestedSessionIdNull() throws Exception {
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getRequestedSessionId(), nullValue());
}
@Test
public void buildRequestUri() {
String uri = requestBuilder.buildRequest(servletContext).getRequestURI();
assertThat(uri, equalTo("/test/this/here"));
}
@Test
public void buildRequestUrl() {
String uri = requestBuilder.buildRequest(servletContext).getRequestURL().toString();
assertThat(uri, equalTo("http://example.com/test/this/here"));
}
@Test
public void buildRequestSchemeHttp() throws Exception {
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getScheme(), equalTo("http"));
}
@Test
public void buildRequestSchemeHttps() throws Exception {
webRequest.setUrl(new URL("https://example.com/"));
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getScheme(), equalTo("https"));
}
@Test
public void buildRequestServerName() throws Exception {
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getServerName(), equalTo("example.com"));
}
@Test
public void buildRequestServerPort() throws Exception {
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getServerPort(), equalTo(80));
}
@Test
public void buildRequestServerPortDefault() throws Exception {
webRequest.setUrl(new URL("https://example.com/"));
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getServerPort(), equalTo(-1));
}
@Test
public void buildRequestServletContext() throws Exception {
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getServletContext(), equalTo(servletContext));
}
@Test
public void buildRequestServletPath() throws Exception {
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getServletPath(), equalTo("/this/here"));
}
@Test
public void buildRequestSession() throws Exception {
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
HttpSession newSession = actualRequest.getSession();
assertThat(newSession, notNullValue());
assertSingleSessionCookie(
"JSESSIONID=" + newSession.getId() + "; Path=/test; Domain=example.com");
webRequest.setAdditionalHeader("Cookie", "JSESSIONID=" + newSession.getId());
requestBuilder = new HtmlUnitRequestBuilder(sessions, webClient, webRequest);
actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getSession(), sameInstance(newSession));
}
@Test
public void buildRequestSessionWithExistingSession() throws Exception {
String sessionId = "session-id";
webRequest.setAdditionalHeader("Cookie", "JSESSIONID=" + sessionId);
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
HttpSession session = actualRequest.getSession();
assertThat(session.getId(), equalTo(sessionId));
assertSingleSessionCookie("JSESSIONID=" + session.getId() + "; Path=/test; Domain=example.com");
requestBuilder = new HtmlUnitRequestBuilder(sessions, webClient, webRequest);
actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getSession(), equalTo(session));
webRequest.setAdditionalHeader("Cookie", "JSESSIONID=" + sessionId + "NEW");
actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getSession(), not(equalTo(session)));
assertSingleSessionCookie("JSESSIONID=" + actualRequest.getSession().getId()
+ "; Path=/test; Domain=example.com");
}
@Test
public void buildRequestSessionTrue() throws Exception {
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
HttpSession session = actualRequest.getSession(true);
assertThat(session, notNullValue());
}
@Test
public void buildRequestSessionFalseIsNull() throws Exception {
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
HttpSession session = actualRequest.getSession(false);
assertThat(session, nullValue());
}
@Test
public void buildRequestSessionFalseWithExistingSession() throws Exception {
String sessionId = "session-id";
webRequest.setAdditionalHeader("Cookie", "JSESSIONID=" + sessionId);
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
HttpSession session = actualRequest.getSession(false);
assertThat(session, notNullValue());
}
@Test
public void buildRequestSessionIsNew() throws Exception {
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getSession().isNew(), equalTo(true));
}
@Test
public void buildRequestSessionIsNewFalse() throws Exception {
String sessionId = "session-id";
webRequest.setAdditionalHeader("Cookie", "JSESSIONID=" + sessionId);
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getSession().isNew(), equalTo(false));
}
@Test
public void buildRequestSessionInvalidate() throws Exception {
String sessionId = "session-id";
webRequest.setAdditionalHeader("Cookie", "JSESSIONID=" + sessionId);
MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);
HttpSession sessionToRemove = actualRequest.getSession();
sessionToRemove.invalidate();
assertThat(sessions.containsKey(sessionToRemove.getId()), equalTo(false));
assertSingleSessionCookie("JSESSIONID=" + sessionToRemove.getId()
+ "; Expires=Thu, 01-Jan-1970 00:00:01 GMT; Path=/test; Domain=example.com");
webRequest.removeAdditionalHeader("Cookie");
requestBuilder = new HtmlUnitRequestBuilder(sessions, webClient, webRequest);
actualRequest = requestBuilder.buildRequest(servletContext);
assertThat(actualRequest.getSession().isNew(), equalTo(true));
assertThat(sessions.containsKey(sessionToRemove.getId()), equalTo(false));
}
// --- setContextPath
@Test
public void setContextPathNull() {
requestBuilder.setContextPath(null);
assertThat(getContextPath(), nullValue());
}
@Test
public void setContextPathEmptyString() {
requestBuilder.setContextPath("");
assertThat(getContextPath(), isEmptyString());
}
@Test(expected = IllegalArgumentException.class)
public void setContextPathDoesNotStartWithSlash() {
requestBuilder.setContextPath("abc/def");
}
@Test(expected = IllegalArgumentException.class)
public void setContextPathEndsWithSlash() {
requestBuilder.setContextPath("/abc/def/");
}
@Test
public void setContextPath() {
String expectedContextPath = "/abc/def";
requestBuilder.setContextPath(expectedContextPath);
assertThat(getContextPath(), equalTo(expectedContextPath));
}
@Test
public void mergeHeader() throws Exception {
String headerName = "PARENT";
String headerValue = "VALUE";
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new HelloController())
.defaultRequest(get("/").header(headerName, headerValue))
.build();
assertThat(mockMvc.perform(requestBuilder).andReturn().getRequest().getHeader(headerName), equalTo(headerValue));
}
@Test
public void mergeSession() throws Exception {
String attrName = "PARENT";
String attrValue = "VALUE";
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new HelloController())
.defaultRequest(get("/").sessionAttr(attrName, attrValue))
.build();
assertThat(mockMvc.perform(requestBuilder).andReturn().getRequest().getSession().getAttribute(attrName), equalTo(attrValue));
}
@Test
public void mergeSessionNotInitialized() throws Exception {
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new HelloController())
.defaultRequest(get("/"))
.build();
assertThat(mockMvc.perform(requestBuilder).andReturn().getRequest().getSession(false), nullValue());
}
@Test
public void mergeParameter() throws Exception {
String paramName = "PARENT";
String paramValue = "VALUE";
String paramValue2 = "VALUE2";
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new HelloController())
.defaultRequest(get("/").param(paramName, paramValue, paramValue2))
.build();
assertThat(Arrays.asList(mockMvc.perform(requestBuilder).andReturn().getRequest().getParameterValues(paramName)), contains(paramValue, paramValue2));
}
@Test
public void mergeCookie() throws Exception {
String cookieName = "PARENT";
String cookieValue = "VALUE";
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new HelloController())
.defaultRequest(get("/").cookie(new Cookie(cookieName,cookieValue)))
.build();
Cookie[] cookies = mockMvc.perform(requestBuilder).andReturn().getRequest().getCookies();
assertThat(cookies, notNullValue());
assertThat(cookies.length, equalTo(1));
Cookie cookie = cookies[0];
assertThat(cookie.getName(), equalTo(cookieName));
assertThat(cookie.getValue(), equalTo(cookieValue));
}
@Test
public void mergeRequestAttribute() throws Exception {
String attrName = "PARENT";
String attrValue = "VALUE";
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new HelloController())
.defaultRequest(get("/").requestAttr(attrName,attrValue))
.build();
assertThat(mockMvc.perform(requestBuilder).andReturn().getRequest().getAttribute(attrName), equalTo(attrValue));
}
private void assertSingleSessionCookie(String expected) {
com.gargoylesoftware.htmlunit.util.Cookie jsessionidCookie = webClient.getCookieManager().getCookie("JSESSIONID");
if (expected == null || expected.contains("Expires=Thu, 01-Jan-1970 00:00:01 GMT")) {
assertThat(jsessionidCookie, nullValue());
return;
}
String actual = jsessionidCookie.getValue();
assertThat("JSESSIONID=" + actual +
"; Path=/test; Domain=example.com", equalTo(expected));
}
private void setParameter(String name, String value) {
webRequest.getRequestParameters().add(new NameValuePair(name, value));
}
private String getContextPath() {
return (String) ReflectionTestUtils.getField(requestBuilder, "contextPath");
}
}

View File

@@ -0,0 +1,155 @@
/*
* Copyright 2002-2015 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.htmlunit;
import java.io.IOException;
import java.net.URL;
import javax.servlet.http.HttpServletRequest;
import com.gargoylesoftware.htmlunit.WebConnection;
import com.gargoylesoftware.htmlunit.WebRequest;
import com.gargoylesoftware.htmlunit.WebResponse;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.mockito.Mockito.mock;
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.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.RestController;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
/**
* @author Rob Winch
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@WebAppConfiguration
public class MockMvcConnectionBuilderSupportTests {
@Autowired
WebApplicationContext context;
MockMvc mockMvc;
WebConnection delegateConnection;
WebConnection connection;
@Before
public void setup() {
delegateConnection = mock(WebConnection.class);
mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
connection = new MockMvcWebConnectionBuilderSupport(mockMvc){}
.createConnection(delegateConnection);
}
@Test(expected = IllegalArgumentException.class)
public void constructorMockMvcNull() {
new MockMvcWebConnectionBuilderSupport((MockMvc)null){};
}
@Test(expected = IllegalArgumentException.class)
public void constructorContextNull() {
new MockMvcWebConnectionBuilderSupport((WebApplicationContext)null){};
}
@Test
public void context() throws Exception {
connection = new MockMvcWebConnectionBuilderSupport(context){}
.createConnection(delegateConnection);
assertMvcProcessed("http://localhost/");
assertDelegateProcessed("http://example.com/");
}
@Test
public void mockMvc() throws Exception {
assertMvcProcessed("http://localhost/");
assertDelegateProcessed("http://example.com/");
}
@Test
public void mockMvcExampleDotCom() throws Exception {
connection = new MockMvcWebConnectionBuilderSupport(context){}
.useMockMvcForHosts("example.com")
.createConnection(delegateConnection);
assertMvcProcessed("http://localhost/");
assertMvcProcessed("http://example.com/");
assertDelegateProcessed("http://other.com/");
}
@Test
public void mockMvcAlwaysUseMockMvc() throws Exception {
connection = new MockMvcWebConnectionBuilderSupport(context){}
.alwaysUseMockMvc()
.createConnection(delegateConnection);
assertMvcProcessed("http://other.com/");
}
@Test
public void defaultContextPathEmpty() throws Exception {
connection = new MockMvcWebConnectionBuilderSupport(context){}
.createConnection(delegateConnection);
assertThat(getWebResponse("http://localhost/abc").getContentAsString(), equalTo(""));;
}
@Test
public void defaultContextPathCustom() throws Exception {
connection = new MockMvcWebConnectionBuilderSupport(context) {
}.contextPath("/abc").createConnection(delegateConnection);
assertThat(getWebResponse("http://localhost/abc/def").getContentAsString(), equalTo("/abc"));;
}
private void assertMvcProcessed(String url) throws Exception {
assertThat(getWebResponse(url), notNullValue());
}
private void assertDelegateProcessed(String url) throws Exception {
assertThat(getWebResponse(url), nullValue());
}
private WebResponse getWebResponse(String url) throws IOException {
return connection.getResponse(new WebRequest(new URL(url)));
}
@Configuration
@EnableWebMvc
static class Config {
@RestController
static class ContextPathController {
@RequestMapping
public String contextPath(HttpServletRequest request) {
return request.getContextPath();
}
}
}
}

View File

@@ -0,0 +1,117 @@
/*
* Copyright 2002-2015 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.htmlunit;
import java.io.IOException;
import java.net.URL;
import javax.servlet.http.HttpServletRequest;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebRequest;
import com.gargoylesoftware.htmlunit.WebResponse;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertThat;
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.Configuration;
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.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
/**
* @author Rob Winch
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@WebAppConfiguration
public class MockMvcWebClientBuilderTests {
@Autowired
WebApplicationContext context;
MockMvc mockMvc;
WebClient webClient;
@Before
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
webClient = new WebClient();
}
@Test(expected = IllegalArgumentException.class)
public void mockMvcSetupNull() {
MockMvcWebClientBuilder.mockMvcSetup(null);
}
@Test(expected = IllegalArgumentException.class)
public void webAppContextSetupNull() {
MockMvcWebClientBuilder.webAppContextSetup(null);
}
@Test
public void mockMvcSetupconfigureWebClient() throws Exception {
webClient = MockMvcWebClientBuilder
.mockMvcSetup(mockMvc)
.configureWebClient(webClient);
assertMvcProcessed("http://localhost/test");
assertDelegateProcessed("http://example.com/");
}
@Test
public void mockMvcSetupCreateWebClient() throws Exception {
webClient = MockMvcWebClientBuilder
.mockMvcSetup(mockMvc)
.createWebClient();
assertMvcProcessed("http://localhost/test");
assertDelegateProcessed("http://example.com/");
}
private void assertMvcProcessed(String url) throws Exception {
assertThat(getWebResponse(url).getContentAsString(), equalTo("mvc"));;
}
private void assertDelegateProcessed(String url) throws Exception {
assertThat(getWebResponse(url).getContentAsString(), not(equalTo("mvc")));
}
private WebResponse getWebResponse(String url) throws IOException {
return webClient.getWebConnection().getResponse(new WebRequest(new URL(url)));
}
@Configuration
@EnableWebMvc
static class Config {
@RestController
static class ContextPathController {
@RequestMapping
public String contextPath(HttpServletRequest request) {
return "mvc";
}
}
}
}

View File

@@ -0,0 +1,92 @@
/*
* Copyright 2002-2015 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.htmlunit;
import java.io.IOException;
import com.gargoylesoftware.htmlunit.Page;
import com.gargoylesoftware.htmlunit.WebClient;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
import org.junit.Before;
import org.junit.Test;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
/**
* @author Rob Winch
*/
public class MockMvcWebConnectionTests {
MockMvc mockMvc;
WebClient webClient;
@Before
public void setup() {
mockMvc = MockMvcBuilders
.standaloneSetup(new HelloController(), new ForwardController())
.build();
webClient = new WebClient();
}
@Test
public void contextPathNull() throws IOException {
webClient.setWebConnection(new MockMvcWebConnection(mockMvc, null));
Page page = webClient.getPage("http://localhost/context/a");
assertThat(page.getWebResponse().getStatusCode(), equalTo(200));;
}
@Test
public void contextPathExplicit() throws IOException {
webClient.setWebConnection(new MockMvcWebConnection(mockMvc, "/context"));
Page page = webClient.getPage("http://localhost/context/a");
assertThat(page.getWebResponse().getStatusCode(), equalTo(200));;
}
@Test
public void contextPathEmpty() throws IOException {
webClient.setWebConnection(new MockMvcWebConnection(mockMvc, ""));
Page page = webClient.getPage("http://localhost/context/a");
assertThat(page.getWebResponse().getStatusCode(), equalTo(200));;
}
@Test
public void forward() throws IOException {
webClient.setWebConnection(new MockMvcWebConnection(mockMvc, ""));
Page page = webClient.getPage("http://localhost/forward");
assertThat(page.getWebResponse().getContentAsString(), equalTo("hello"));;
}
@Test(expected = IllegalArgumentException.class)
public void contextPathDoesNotStartWithSlash() throws IOException {
new MockMvcWebConnection(mockMvc, "context");
}
@Test(expected = IllegalArgumentException.class)
public void contextPathEndsWithSlash() throws IOException {
new MockMvcWebConnection(mockMvc, "/context/");
}
}

View File

@@ -0,0 +1,135 @@
/*
* Copyright 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.htmlunit;
import java.net.URL;
import java.util.List;
import com.gargoylesoftware.htmlunit.WebRequest;
import com.gargoylesoftware.htmlunit.WebResponse;
import com.gargoylesoftware.htmlunit.util.NameValuePair;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletResponse;
/**
*
* @author Rob Winch
*/
public class MockWebResponseBuilderTests {
private WebRequest webRequest;
private MockHttpServletResponse httpServletResponse;
private MockWebResponseBuilder responseBuilder;
@Before
public void setUp() throws Exception {
webRequest = new WebRequest(new URL("http://example.com:80/test/this/here"));
httpServletResponse = new MockHttpServletResponse();
responseBuilder = new MockWebResponseBuilder(System.currentTimeMillis(), webRequest, httpServletResponse);
}
// --- constructor
@Test(expected = IllegalArgumentException.class)
public void constructorNullWebRequest() {
new MockWebResponseBuilder(0L, null, httpServletResponse);
}
@Test(expected = IllegalArgumentException.class)
public void constructorNullResponse() throws Exception {
new MockWebResponseBuilder(0L, new WebRequest(new URL("http://example.com:80/test/this/here")), null);
}
// --- build
@Test
public void buildContent() throws Exception {
httpServletResponse.getWriter().write("expected content");
WebResponse webResponse = responseBuilder.build();
assertThat(webResponse.getContentAsString(), equalTo("expected content"));;
}
@Test
public void buildContentCharset() throws Exception {
httpServletResponse.addHeader("Content-Type", "text/html; charset=UTF-8");
WebResponse webResponse = responseBuilder.build();
assertThat(webResponse.getContentCharset(), equalTo("UTF-8"));;
}
@Test
public void buildContentType() throws Exception {
httpServletResponse.addHeader("Content-Type", "text/html; charset-UTF-8");
WebResponse webResponse = responseBuilder.build();
assertThat(webResponse.getContentType(), equalTo("text/html"));;
}
@Test
public void buildResponseHeaders() throws Exception {
httpServletResponse.addHeader("Content-Type", "text/html");
httpServletResponse.addHeader("X-Test", "value");
WebResponse webResponse = responseBuilder.build();
List<NameValuePair> responseHeaders = webResponse.getResponseHeaders();
assertThat(responseHeaders.size(), equalTo(2));;
NameValuePair header = responseHeaders.get(0);
assertThat(header.getName(), equalTo("Content-Type"));;
assertThat(header.getValue(), equalTo("text/html"));;
header = responseHeaders.get(1);
assertThat(header.getName(), equalTo("X-Test"));;
assertThat(header.getValue(), equalTo("value"));;
}
@Test
public void buildStatus() throws Exception {
WebResponse webResponse = responseBuilder.build();
assertThat(webResponse.getStatusCode(), equalTo(200));;
assertThat(webResponse.getStatusMessage(), equalTo("OK"));;
}
@Test
public void buildStatusNotOk() throws Exception {
httpServletResponse.setStatus(401);
WebResponse webResponse = responseBuilder.build();
assertThat(webResponse.getStatusCode(), equalTo(401));;
assertThat(webResponse.getStatusMessage(), equalTo("Unauthorized"));;
}
@Test
public void buildStatusCustomMessage() throws Exception {
httpServletResponse.sendError(401, "Custom");
WebResponse webResponse = responseBuilder.build();
assertThat(webResponse.getStatusCode(), equalTo(401));;
assertThat(webResponse.getStatusMessage(), equalTo("Custom"));;
}
@Test
public void buildWebRequest() throws Exception {
WebResponse webResponse = responseBuilder.build();
assertThat(webResponse.getWebRequest(), equalTo(webRequest));;
}
}

View File

@@ -0,0 +1,43 @@
/*
* Copyright 2002-2015 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.htmlunit;
import java.net.URL;
import com.gargoylesoftware.htmlunit.WebRequest;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import org.junit.Test;
import org.springframework.test.web.servlet.htmlunit.UrlRegexRequestMatcher;
import org.springframework.test.web.servlet.htmlunit.WebRequestMatcher;
/**
* @author Rob Winch
*/
public class UrlRegexRequestMatcherTests {
@Test
public void classlevelJavadoc() throws Exception {
WebRequestMatcher cdnMatcher = new UrlRegexRequestMatcher(".*?//code.jquery.com/.*");
boolean matches = cdnMatcher.matches(new WebRequest(new URL("http://code.jquery.com/jquery-1.11.0.min.js")));
assertThat(matches, equalTo(true));
matches = cdnMatcher.matches(new WebRequest(new URL("http://localhost/jquery-1.11.0.min.js")));
assertThat(matches, equalTo(false));
}
}

View File

@@ -0,0 +1,136 @@
/*
* Copyright 2002-2015 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.htmlunit.webdriver;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
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.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.RestController;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
/**
* @author Rob Winch
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@WebAppConfiguration
public class MockMvcHtmlUnitDriverBuilderTests {
public static final String EXPECTED_BODY = "MockMvcHtmlUnitDriverBuilderTests mvc";
@Autowired
WebApplicationContext context;
MockMvc mockMvc;
HtmlUnitDriver driver;
@Before
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
}
@Test(expected = IllegalArgumentException.class)
public void mockMvcSetupNull() {
MockMvcHtmlUnitDriverBuilder.mockMvcSetup(null);
}
@Test(expected = IllegalArgumentException.class)
public void webAppContextSetupNull() {
MockMvcHtmlUnitDriverBuilder.webAppContextSetup(null);
}
@Test
public void mockMvcSetupConfigureDriver() throws Exception {
driver = MockMvcHtmlUnitDriverBuilder
.mockMvcSetup(mockMvc)
.configureDriver(new WebConnectionHtmlUnitDriver());
assertMvcProcessed("http://localhost/test");
assertDelegateProcessed("http://example.com/");
}
@Test
public void mockMvcSetupCreateDriver() throws Exception {
driver = MockMvcHtmlUnitDriverBuilder
.mockMvcSetup(mockMvc)
.createDriver();
assertMvcProcessed("http://localhost/test");
assertDelegateProcessed("http://example.com/");
}
@Test
public void javascriptEnabledDefaultEnabled() {
driver = MockMvcHtmlUnitDriverBuilder
.mockMvcSetup(mockMvc)
.createDriver();
assertThat(driver.isJavascriptEnabled(), equalTo(true));
}
@Test
public void javascriptEnabledDisabled() {
driver = MockMvcHtmlUnitDriverBuilder
.mockMvcSetup(mockMvc)
.javascriptEnabled(false)
.createDriver();
assertThat(driver.isJavascriptEnabled(), equalTo(false));
}
private void assertMvcProcessed(String url) throws Exception {
assertThat(get(url), containsString(EXPECTED_BODY));
}
private void assertDelegateProcessed(String url) throws Exception {
assertThat(get(url), not(containsString(EXPECTED_BODY)));
}
private String get(String url) throws IOException {
driver.get(url);
return driver.getPageSource();
}
@Configuration
@EnableWebMvc
static class Config {
@RestController
static class ContextPathController {
@RequestMapping
public String contextPath(HttpServletRequest request) {
return EXPECTED_BODY;
}
}
}
}

View File

@@ -0,0 +1,55 @@
package org.springframework.test.web.servlet.htmlunit.webdriver;
import com.gargoylesoftware.htmlunit.WebConnection;
import com.gargoylesoftware.htmlunit.WebRequest;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.fail;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.mockito.Matchers.any;
import org.mockito.Mock;
import static org.mockito.Mockito.when;
import org.mockito.runners.MockitoJUnitRunner;
/**
* @author Rob Winch
*/
// tag::junit-spring-setup[]
@RunWith(MockitoJUnitRunner.class)
public class WebConnectionHtmlUnitDriverTests {
@Mock
WebConnection connection;
WebConnectionHtmlUnitDriver driver;
@Before
public void setup() throws Exception {
driver = new WebConnectionHtmlUnitDriver();
when(connection.getResponse(any(WebRequest.class))).thenThrow(new InternalError(""));
}
@Test
public void getWebConnectionDefaultNotNull() {
assertThat(driver.getWebConnection(), notNullValue());
}
@Test
public void setWebConnection() {
driver.setWebConnection(connection);
assertThat(driver.getWebConnection(), equalTo(connection));
try {
driver.get("https://example.com");
fail("Expected Exception");
} catch (InternalError success) {}
}
@Test(expected = IllegalArgumentException.class)
public void setWebConnectionNull() {
driver.setWebConnection(null);
}
}