4 |
5 |
6 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | rootProject.name = 'spring-test-htmlunit-build'
2 |
3 | include 'spring-test-htmlunit'
4 | include 'mail-webapp'
5 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/spring-attic/spring-test-htmlunit/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/mail-webapp/src/test/resources/GebConfig.groovy:
--------------------------------------------------------------------------------
1 | reportsDir = 'build/geb-reports/'
2 | baseUrl = System.getProperty('geb.build.baseUrl','http://localhost:8080/')
3 | driver = { new org.openqa.selenium.htmlunit.HtmlUnitDriver(true) }
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Fri Mar 14 16:18:45 CDT 2014
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=http\://services.gradle.org/distributions/gradle-2.4-all.zip
7 |
--------------------------------------------------------------------------------
/README.adoc:
--------------------------------------------------------------------------------
1 | = Spring MVC Test HtmlUnit
2 | Rob Winch
3 |
4 | This project has been merged http://docs.spring.io/spring/docs/4.2.0.BUILD-SNAPSHOT/spring-framework-reference/htmlsingle/#spring-mvc-test-server-htmlunit[into spring-test-4.2.0.RELEASE]. The spring-test-html project is not being maintained separately anymore. Please report issues at https://jira.spring.io/browse/SPR
5 |
--------------------------------------------------------------------------------
/spring-test-htmlunit/src/main/java/org/springframework/test/web/servlet/htmlunit/matchers/WebRequestMatcher.java:
--------------------------------------------------------------------------------
1 | package org.springframework.test.web.servlet.htmlunit.matchers;
2 |
3 | import com.gargoylesoftware.htmlunit.WebRequest;
4 |
5 | /**
6 | * Strategy to match on a WebRequest
7 | *
8 | * @author Rob Winch
9 | */
10 | public interface WebRequestMatcher {
11 | /**
12 | * Return true if matches on WebRequest, else false
13 | *
14 | * @param request the WebRequest to attempt to match on
15 | * @return true if matches on WebRequest, else false
16 | */
17 | boolean matches(WebRequest request);
18 | }
19 |
--------------------------------------------------------------------------------
/mail-webapp/src/main/resources/log4j.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/spring-test-htmlunit/build.gradle:
--------------------------------------------------------------------------------
1 | description = 'Provides integration between Spring MVC Test and HtmlUnit'
2 |
3 |
4 | dependencies {
5 | compile "org.springframework:spring-test:$springVersion",
6 | "org.springframework:spring-context:$springVersion",
7 | "org.springframework:spring-web:$springVersion",
8 | "net.sourceforge.htmlunit:htmlunit:$htmlunitVersion"
9 |
10 | optional "org.seleniumhq.selenium:selenium-htmlunit-driver:$seleniumVersion"
11 |
12 | provided "javax.servlet:javax.servlet-api:$servletApiVersion"
13 |
14 | testCompile 'org.easytesting:fest-assert:1.4',
15 | "org.springframework:spring-webmvc:$springVersion",
16 | "junit:junit:$junitVersion",
17 | "org.mockito:mockito-all:$mockitoVersion"
18 |
19 | jacoco "org.jacoco:org.jacoco.agent:$jacocoVersion:runtime"
20 | }
--------------------------------------------------------------------------------
/mail-webapp/src/main/java/sample/data/MessageRepository.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 | package sample.data;
14 |
15 | import org.springframework.data.repository.CrudRepository;
16 |
17 | /**
18 | *
19 | * @author Rob Winch
20 | *
21 | */
22 | public interface MessageRepository extends CrudRepository {
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/src/test/java/docs/webdriver/why/ViewMessagePage.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2002-2015 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5 | * use this file except in compliance with the License. You may obtain a copy of
6 | * the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations under
14 | * the License.
15 | */
16 | package docs.webdriver.why;
17 |
18 | import com.gargoylesoftware.htmlunit.html.HtmlPage;
19 |
20 | /**
21 | * @author Rob Winch
22 | */
23 | public class ViewMessagePage {
24 | public ViewMessagePage(HtmlPage page) {}
25 | }
26 |
--------------------------------------------------------------------------------
/mail-webapp/src/test/java/sample/fest/Assertions.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2002-2013 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5 | * use this file except in compliance with the License. You may obtain a copy of
6 | * the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations under
14 | * the License.
15 | */
16 | package sample.fest;
17 |
18 | import sample.data.Message;
19 |
20 | /**
21 | * @author Rob Winch
22 | */
23 | public class Assertions extends org.fest.assertions.Assertions {
24 |
25 | public static MessageAssert assertThat(Message message) {
26 | return new MessageAssert(message);
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/mail-webapp/src/test/groovy/sample/geb/pages/MessageRow.groovy:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 | package sample.geb.pages
14 |
15 | import geb.Module
16 |
17 |
18 | /**
19 | * Represents a Message when viewed in a list view
20 | * @author Rob Winch
21 | *
22 | */
23 | class MessageRow extends Module {
24 | static content = {
25 | cell { $("td", it) }
26 | user { cell(0).text() }
27 | subject { cell(1).text() }
28 | link { cell(1).$('a') }
29 | }
30 | }
--------------------------------------------------------------------------------
/mail-webapp/src/main/java/sample/config/WebSecurityAppInitializer.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2002-2013 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5 | * use this file except in compliance with the License. You may obtain a copy of
6 | * the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations under
14 | * the License.
15 | */
16 | package sample.config;
17 |
18 | import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
19 |
20 | /**
21 | * @author Rob Winch
22 | */
23 | public class WebSecurityAppInitializer extends AbstractSecurityWebApplicationInitializer {
24 | public WebSecurityAppInitializer() {
25 | super(WebSecurityConfig.class);
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/mail-webapp/src/main/webapp/WEB-INF/templates/messages/view.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Messages : View
6 |
7 |
8 |
9 |
A detailed message that is longer than the summary.
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/spring-test-htmlunit/src/test/java/org/springframework/test/web/servlet/htmlunit/ForwardController.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2002-2015 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5 | * use this file except in compliance with the License. You may obtain a copy of
6 | * the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations under
14 | * the License.
15 | */
16 | package org.springframework.test.web.servlet.htmlunit;
17 |
18 | import org.springframework.stereotype.Controller;
19 | import org.springframework.web.bind.annotation.RequestMapping;
20 |
21 | /**
22 | * @author Rob Winch
23 | */
24 | @Controller
25 | public class ForwardController {
26 |
27 | @RequestMapping("/forward")
28 | public String forward() {
29 | return "forward:/";
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/spring-test-htmlunit/src/main/webapp/WEB-INF/web.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | Sample Application
6 |
7 |
8 | contextConfigLocation
9 |
10 | /WEB-INF/spring/*.xml
11 |
12 |
13 |
14 |
15 | org.springframework.web.context.ContextLoaderListener
16 |
17 |
18 |
19 | message
20 | org.springframework.web.servlet.DispatcherServlet
21 | 1
22 |
23 |
24 |
25 | message
26 | /
27 |
28 |
29 |
30 | index.jsp
31 |
32 |
33 |
--------------------------------------------------------------------------------
/mail-webapp/src/test/groovy/sample/geb/pages/CreateMessagePage.groovy:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 | package sample.geb.pages
14 |
15 | import geb.Page
16 |
17 |
18 | /**
19 | * Represents the page that a {@link Message} is created on.
20 | *
21 | * @author Rob Winch
22 | *
23 | */
24 | // tag::class[]
25 | class CreateMessagePage extends Page {
26 | static at = { assert title == 'Messages : Create'; true }
27 | static url = 'messages/form'
28 | static content = {
29 | submit { $('input[type=submit]') }
30 | form { $('form') }
31 | errors(required:false) { $('label.error, .alert-error')?.text() }
32 | }
33 | }
34 | // end::class[]
--------------------------------------------------------------------------------
/mail-webapp/src/test/groovy/sample/geb/pages/ViewMessagePage.groovy:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 | package sample.geb.pages
14 |
15 |
16 | import geb.Page
17 |
18 |
19 | /**
20 | * Represents the page where a {@link Message} details can be viewed.
21 | * @author Rob Winch
22 | *
23 | */
24 | class ViewMessagePage extends Page {
25 | static at = { assert title == 'Messages : View'; true }
26 | static url = 'messages/'
27 | static content = {
28 | success(required:false) { $('.alert-success')?.text() }
29 | id { $('dd')[0].text() }
30 | date { $('dd')[1].text() }
31 | summary { $('dd')[2].text() }
32 | message { $('dd')[3].text() }
33 | }
34 | }
--------------------------------------------------------------------------------
/mail-webapp/src/main/webapp/WEB-INF/templates/messages/list.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Messages : View all
6 |
7 |
8 |
9 |
34 |
35 |
--------------------------------------------------------------------------------
/mail-webapp/src/test/groovy/sample/geb/pages/LoginPage.groovy:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 | package sample.geb.pages
14 |
15 | import geb.Page
16 |
17 |
18 | /**
19 | * Represents the page that a {@link Message} is created on.
20 | *
21 | * @author Rob Winch
22 | *
23 | */
24 | class LoginPage extends Page {
25 | static at = { assert title == 'Login Page'; true }
26 | static url = 'login'
27 |
28 | static content = {
29 | usernameInput { $("input[name=username]") }
30 | passwordInput { $("input[name=password]") }
31 | submitButton { $("input[type=submit]") }
32 | }
33 |
34 | void login(username='user',password='password') {
35 | usernameInput = username
36 | passwordInput = password
37 | submitButton.click()
38 | }
39 | }
--------------------------------------------------------------------------------
/spring-test-htmlunit/src/test/java/org/springframework/test/web/servlet/htmlunit/HelloController.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2002-2013 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5 | * use this file except in compliance with the License. You may obtain a copy of
6 | * the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations under
14 | * the License.
15 | */
16 | package org.springframework.test.web.servlet.htmlunit;
17 |
18 | import org.springframework.stereotype.Controller;
19 | import org.springframework.web.bind.annotation.RequestMapping;
20 | import org.springframework.web.bind.annotation.ResponseBody;
21 | import org.springframework.web.bind.annotation.RestController;
22 |
23 | import javax.servlet.http.HttpServletRequest;
24 |
25 | /**
26 | * @author Rob Winch
27 | */
28 | @Controller
29 | public class HelloController {
30 | @RequestMapping
31 | @ResponseBody
32 | public String header(HttpServletRequest request) {
33 | return "hello";
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/mail-webapp/src/main/java/sample/config/WebMvcAppInitializer.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2002-2013 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5 | * use this file except in compliance with the License. You may obtain a copy of
6 | * the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations under
14 | * the License.
15 | */
16 | package sample.config;
17 |
18 | import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
19 |
20 | /**
21 | * @author Rob Winch
22 | */
23 | public class WebMvcAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
24 | @Override
25 | protected Class>[] getRootConfigClasses() {
26 | return null;
27 | }
28 |
29 | @Override
30 | protected Class>[] getServletConfigClasses() {
31 | return new Class[] { DataConfig.class, WebMvcConfig.class};
32 | }
33 |
34 | @Override
35 | protected String[] getServletMappings() {
36 | return new String[] { "/"};
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/spring-test-htmlunit/src/main/webapp/WEB-INF/templates/messages/list.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Messages : View all
6 |
7 |
8 |
9 |
34 |
35 |
--------------------------------------------------------------------------------
/src/test/java/docs/webdriver/why/WhyWebDriversTests.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2002-2015 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5 | * use this file except in compliance with the License. You may obtain a copy of
6 | * the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations under
14 | * the License.
15 | */
16 | package docs.webdriver.why;
17 |
18 | import com.gargoylesoftware.htmlunit.html.HtmlPage;
19 | import com.gargoylesoftware.htmlunit.html.HtmlTextInput;
20 |
21 | /**
22 | * @author Rob Winch
23 | */
24 | public class WhyWebDriversTests {
25 |
26 | // tag::create-message[]
27 | public HtmlPage createMessage(HtmlPage currentPage, String summary, String text) {
28 | setSummary(currentPage, summary);
29 | // end::create-message[]
30 | return null;
31 | }
32 |
33 | // tag::set-summary[]
34 | public void setSummary(HtmlPage currentPage, String summary) {
35 | // tag::set-summary-input[]
36 | HtmlTextInput summaryInput = currentPage.getHtmlElementById("summary");
37 | summaryInput.setValueAttribute(summary);
38 | // end::set-summary-input[]
39 | }
40 | // end::set-summary[]
41 | }
42 |
--------------------------------------------------------------------------------
/mail-webapp/src/main/java/sample/config/WebSecurityConfig.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2002-2013 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5 | * use this file except in compliance with the License. You may obtain a copy of
6 | * the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations under
14 | * the License.
15 | */
16 | package sample.config;
17 |
18 | import org.springframework.beans.factory.annotation.Autowired;
19 | import org.springframework.context.annotation.Configuration;
20 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
21 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
22 | import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity;
23 |
24 | /**
25 | * @author Rob Winch
26 | */
27 | @EnableWebMvcSecurity
28 | @Configuration
29 | public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
30 | @Autowired
31 | public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
32 | auth
33 | .inMemoryAuthentication()
34 | .withUser("user").password("password").roles("USER");
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/spring-test-htmlunit/src/test/java/org/springframework/test/web/servlet/htmlunit/matchers/UrlRegexRequestMatcherTests.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2002-2013 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5 | * use this file except in compliance with the License. You may obtain a copy of
6 | * the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations under
14 | * the License.
15 | */
16 | package org.springframework.test.web.servlet.htmlunit.matchers;
17 |
18 | import com.gargoylesoftware.htmlunit.WebRequest;
19 | import org.junit.Before;
20 | import org.junit.Test;
21 |
22 | import java.net.URL;
23 |
24 | import static org.fest.assertions.Assertions.assertThat;
25 |
26 | /**
27 | * @author Rob Winch
28 | */
29 | public class UrlRegexRequestMatcherTests {
30 |
31 | @Test
32 | public void classlevelJavadoc() throws Exception {
33 | WebRequestMatcher cdnMatcher = new UrlRegexRequestMatcher(".*?//code.jquery.com/.*");
34 |
35 | boolean matches = cdnMatcher.matches(new WebRequest(new URL("http://code.jquery.com/jquery-1.11.0.min.js")));
36 | assertThat(matches).isTrue();
37 |
38 | matches = cdnMatcher.matches(new WebRequest(new URL("http://localhost/jquery-1.11.0.min.js")));
39 | assertThat(matches).isFalse();
40 | }
41 | }
--------------------------------------------------------------------------------
/mail-webapp/src/test/java/sample/webdriver/pages/AbstractPage.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 | package sample.webdriver.pages;
14 |
15 | import org.openqa.selenium.WebDriver;
16 | import org.openqa.selenium.WebElement;
17 | import org.openqa.selenium.support.FindBy;
18 |
19 | /**
20 | * Represents the common elements in a page within the message application.
21 | *
22 | * @author Rob Winch
23 | *
24 | */
25 | public class AbstractPage {
26 | protected WebDriver driver;
27 |
28 | @FindBy(css = "label.error, .alert-error")
29 | private WebElement errors;
30 |
31 | public AbstractPage(WebDriver driver) {
32 | setDriver(driver);
33 | }
34 |
35 | public void setDriver(WebDriver driver) {
36 | this.driver = driver;
37 | }
38 |
39 | public String getErrors() {
40 | return errors.getText();
41 | }
42 |
43 | static void get(WebDriver driver, String relativeUrl) {
44 | String url = System.getProperty("geb.build.baseUrl","http://localhost:9990/") + relativeUrl;
45 | driver.get(url);
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/mail-webapp/src/main/webapp/WEB-INF/templates/messages/form.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Messages : Create
5 |
6 |
7 |
8 |
9 |
Messages : Create
10 |
23 |
24 |
25 |
26 |
33 |
34 |
--------------------------------------------------------------------------------
/spring-test-htmlunit/src/main/java/org/springframework/test/web/servlet/htmlunit/ForwardRequestPostProcessor.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2002-2015 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5 | * use this file except in compliance with the License. You may obtain a copy of
6 | * the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations under
14 | * the License.
15 | */
16 |
17 | package org.springframework.test.web.servlet.htmlunit;
18 |
19 | import org.springframework.beans.Mergeable;
20 | import org.springframework.mock.web.MockHttpServletRequest;
21 | import org.springframework.test.web.servlet.RequestBuilder;
22 | import org.springframework.test.web.servlet.SmartRequestBuilder;
23 | import org.springframework.test.web.servlet.request.RequestPostProcessor;
24 | import org.springframework.util.Assert;
25 |
26 | /**
27 | * @author Rob Winch
28 | */
29 | final class ForwardRequestPostProcessor implements RequestPostProcessor {
30 | private final String forwardUrl;
31 |
32 | public ForwardRequestPostProcessor(String url) {
33 | Assert.hasText(url, "Forward url must have text");
34 | forwardUrl = url;
35 | }
36 |
37 | @Override
38 | public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) {
39 | request.setServletPath(forwardUrl);
40 | return request;
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/spring-test-htmlunit/src/main/webapp/WEB-INF/spring/spring-data.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
--------------------------------------------------------------------------------
/spring-test-htmlunit/src/test/java/org/springframework/test/web/servlet/htmlunit/webdriver/WebConnectionHtmlUnitDriverTests.java:
--------------------------------------------------------------------------------
1 | package org.springframework.test.web.servlet.htmlunit.webdriver;
2 |
3 | import com.gargoylesoftware.htmlunit.WebConnection;
4 | import com.gargoylesoftware.htmlunit.WebRequest;
5 | import static org.fest.assertions.Assertions.assertThat;
6 | import static org.junit.Assert.fail;
7 | import org.junit.Before;
8 | import org.junit.Test;
9 | import org.junit.runner.RunWith;
10 | import static org.mockito.Matchers.any;
11 | import org.mockito.Mock;
12 | import static org.mockito.Mockito.when;
13 | import org.mockito.runners.MockitoJUnitRunner;
14 |
15 | /**
16 | * @author Rob Winch
17 | */
18 | // tag::junit-spring-setup[]
19 | @RunWith(MockitoJUnitRunner.class)
20 | public class WebConnectionHtmlUnitDriverTests {
21 | @Mock
22 | WebConnection connection;
23 |
24 | WebConnectionHtmlUnitDriver driver;
25 |
26 | @Before
27 | public void setup() throws Exception {
28 | driver = new WebConnectionHtmlUnitDriver();
29 |
30 | when(connection.getResponse(any(WebRequest.class))).thenThrow(new InternalError(""));
31 | }
32 |
33 | @Test
34 | public void getWebConnectionDefaultNotNull() {
35 | assertThat(driver.getWebConnection()).isNotNull();
36 | }
37 |
38 | @Test
39 | public void setWebConnection() {
40 | driver.setWebConnection(connection);
41 |
42 | assertThat(driver.getWebConnection()).isEqualTo(connection);
43 | try {
44 | driver.get("https://example.com");
45 | fail("Expected Exception");
46 | } catch (InternalError success) {}
47 | }
48 |
49 | @Test(expected = IllegalArgumentException.class)
50 | public void setWebConnectionNull() {
51 | driver.setWebConnection(null);
52 | }
53 | }
--------------------------------------------------------------------------------
/spring-test-htmlunit/src/main/webapp/WEB-INF/templates/messages/form.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Messages : Create
6 |
7 |
8 |
9 |
10 |
Messages : Create
11 |
24 |
25 |
26 |
27 |
34 |
35 |
--------------------------------------------------------------------------------
/mail-webapp/src/test/java/sample/webdriver/pages/LoginPage.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 | package sample.webdriver.pages;
14 |
15 | import org.openqa.selenium.WebDriver;
16 | import org.openqa.selenium.WebElement;
17 | import org.openqa.selenium.support.FindBy;
18 | import org.openqa.selenium.support.PageFactory;
19 |
20 | /**
21 | * Represents the page where a {@link sample.data.Message} is created.
22 | *
23 | * @author Rob Winch
24 | *
25 | */
26 | public class LoginPage extends AbstractPage {
27 |
28 | private WebElement username;
29 |
30 | private WebElement password;
31 |
32 | private WebElement submit;
33 |
34 | public LoginPage(WebDriver driver) {
35 | super(driver);
36 | }
37 |
38 | public void login(String username, String password) {
39 | this.username.sendKeys(username);
40 | this.password.sendKeys(password);
41 | this.submit.click();
42 | }
43 |
44 | public static void login(WebDriver driver) {
45 | get(driver, "login");
46 | LoginPage loginPage = PageFactory.initElements(driver, LoginPage.class);
47 | loginPage.login("user","password");
48 | }
49 | }
--------------------------------------------------------------------------------
/spring-test-htmlunit/src/main/webapp/WEB-INF/message-servlet.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
10 |
11 |
12 |
14 |
15 |
16 |
18 |
19 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
--------------------------------------------------------------------------------
/spring-test-htmlunit/src/main/java/org/springframework/test/web/servlet/htmlunit/matchers/UrlRegexRequestMatcher.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2002-2013 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5 | * use this file except in compliance with the License. You may obtain a copy of
6 | * the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations under
14 | * the License.
15 | */
16 | package org.springframework.test.web.servlet.htmlunit.matchers;
17 |
18 | import com.gargoylesoftware.htmlunit.WebRequest;
19 |
20 | import java.util.regex.Pattern;
21 |
22 | /**
23 | *
24 | * An implementation of WebRequestMatcher that allows matching on WebRequest#getUrl().toExternalForm() using a regular expression. For example, if you would like to match on the domain code.jquery.com, you might want to use the following:
29 | *
30 | * @author Rob Winch
31 | * @see org.springframework.test.web.servlet.htmlunit.DelegatingWebConnection
32 | */
33 | public final class UrlRegexRequestMatcher implements WebRequestMatcher {
34 | private Pattern pattern;
35 |
36 | public UrlRegexRequestMatcher(String regex) {
37 | pattern = Pattern.compile(regex);
38 | }
39 |
40 | public UrlRegexRequestMatcher(Pattern pattern) {
41 | this.pattern = pattern;
42 | }
43 |
44 | @Override
45 | public boolean matches(WebRequest request) {
46 | String url = request.getUrl().toExternalForm();
47 | return pattern.matcher(url).matches();
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/src/test/java/docs/webdriver/why/CreateMessagePage.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2002-2015 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5 | * use this file except in compliance with the License. You may obtain a copy of
6 | * the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations under
14 | * the License.
15 | */
16 | package docs.webdriver.why;
17 |
18 | import com.gargoylesoftware.htmlunit.html.HtmlPage;
19 | import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
20 | import com.gargoylesoftware.htmlunit.html.HtmlTextInput;
21 |
22 | /**
23 | * @author Rob Winch
24 | */
25 | // tag::class[]
26 | public class CreateMessagePage {
27 | HtmlPage currentPage;
28 |
29 | HtmlTextInput summaryInput;
30 |
31 | HtmlSubmitInput submit;
32 |
33 | public CreateMessagePage(HtmlPage currentPage) {
34 | this.currentPage = currentPage;
35 | this.summaryInput = currentPage.getHtmlElementById("summary");
36 | this.submit = currentPage.getHtmlElementById("submit");
37 | }
38 |
39 | public T createMessage(String summary, String text) throws Exception {
40 | setSummary(summary);
41 |
42 | HtmlPage result = submit.click();
43 | boolean error = CreateMessagePage.at(result);
44 |
45 | return (T) (error ? new CreateMessagePage(result) : new ViewMessagePage(result));
46 | }
47 |
48 | public void setSummary(String summary) throws Exception {
49 | summaryInput.setValueAttribute(summary);
50 | }
51 |
52 | public static boolean at(HtmlPage page) {
53 | return "Create Message".equals(page.getTitleText());
54 | }
55 | }
56 | // end::class[]
57 |
--------------------------------------------------------------------------------
/mail-webapp/src/test/java/sample/fest/MessageAssert.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2002-2013 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5 | * use this file except in compliance with the License. You may obtain a copy of
6 | * the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations under
14 | * the License.
15 | */
16 | package sample.fest;
17 |
18 | import org.fest.assertions.ObjectAssert;
19 | import org.springframework.test.util.MatcherAssertionErrors;
20 | import sample.data.Message;
21 |
22 | import java.util.Calendar;
23 |
24 | import static org.fest.assertions.Assertions.assertThat;
25 |
26 | /**
27 | * @author Rob Winch
28 | */
29 | public class MessageAssert extends ObjectAssert {
30 |
31 | public MessageAssert(Message message) {
32 | super(message);
33 | }
34 |
35 | @Override
36 | public MessageAssert isEqualTo(Object expected) {
37 | isEqualToIgnoringGeneratedFields(expected);
38 | Message expectedMessage = (Message) expected;
39 | Message actualMessage = (Message) actual;
40 | assertThat(actualMessage.getId()).isEqualTo(expectedMessage.getId());
41 | assertThat(actualMessage.getCreated()).isEqualTo(expectedMessage.getCreated());
42 | return this;
43 | }
44 |
45 | public MessageAssert isEqualToIgnoringGeneratedFields(Object expected) {
46 | assertThat(expected).isInstanceOf(Message.class);
47 | Message expectedMessage = (Message) expected;
48 | Message actualMessage = (Message) actual;
49 | assertThat(actualMessage.getSummary()).isEqualTo(expectedMessage.getSummary());
50 | assertThat(actualMessage.getText()).isEqualTo(expectedMessage.getText());
51 | return this;
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/mail-webapp/src/main/java/sample/data/Message.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 | package sample.data;
14 |
15 | import java.util.Calendar;
16 |
17 | import javax.persistence.Entity;
18 | import javax.persistence.GeneratedValue;
19 | import javax.persistence.GenerationType;
20 | import javax.persistence.Id;
21 | import javax.persistence.Version;
22 |
23 | import org.hibernate.validator.constraints.NotEmpty;
24 |
25 | /**
26 | *
27 | * @author Rob Winch
28 | *
29 | */
30 | @Entity
31 | public class Message {
32 | @Id
33 | @GeneratedValue(strategy = GenerationType.AUTO)
34 | private Long id;
35 |
36 | @NotEmpty(message = "Message is required.")
37 | private String text;
38 |
39 | @NotEmpty(message = "Summary is required.")
40 | private String summary;
41 |
42 | @Version
43 | private Calendar created = Calendar.getInstance();
44 |
45 | public Long getId() {
46 | return id;
47 | }
48 |
49 | public void setId(Long id) {
50 | this.id = id;
51 | }
52 |
53 | public Calendar getCreated() {
54 | return created;
55 | }
56 |
57 | public void setCreated(Calendar created) {
58 | this.created = created;
59 | }
60 |
61 | public String getText() {
62 | return text;
63 | }
64 |
65 | public void setText(String text) {
66 | this.text = text;
67 | }
68 |
69 | public String getSummary() {
70 | return summary;
71 | }
72 |
73 | public void setSummary(String summary) {
74 | this.summary = summary;
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/mail-webapp/src/test/java/sample/webdriver/pages/CreateMessagePage.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 | package sample.webdriver.pages;
14 |
15 | import org.openqa.selenium.WebDriver;
16 | import org.openqa.selenium.WebElement;
17 | import org.openqa.selenium.support.FindBy;
18 | import org.openqa.selenium.support.PageFactory;
19 | import sample.data.Message;
20 |
21 | /**
22 | * Represents the page where a {@link Message} is created.
23 | *
24 | * @author Rob Winch
25 | *
26 | */
27 | // tag::class[]
28 | public class CreateMessagePage
29 | extends AbstractPage { // <1>
30 |
31 | // <2>
32 | private WebElement summary;
33 |
34 | private WebElement text;
35 |
36 | // <3>
37 | @FindBy(css = "input[type=submit]")
38 | private WebElement submit;
39 |
40 | public CreateMessagePage(WebDriver driver) {
41 | super(driver);
42 | }
43 |
44 | public T createMessage(Class resultPage, String summary, String details) {
45 | this.summary.sendKeys(summary);
46 | this.text.sendKeys(details);
47 | this.submit.click();
48 | return PageFactory.initElements(driver, resultPage);
49 | }
50 |
51 | public static CreateMessagePage to(WebDriver driver) {
52 | // driver.get("http://localhost:8080/messages/form");
53 | get(driver, "messages/form");
54 | return PageFactory.initElements(driver, CreateMessagePage.class);
55 | }
56 | }
57 | // tag::class[]
--------------------------------------------------------------------------------
/publish-maven.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'maven'
2 |
3 | ext.optionalDeps = []
4 | ext.providedDeps = []
5 |
6 | ext.optional = { optionalDeps << it }
7 | ext.provided = { providedDeps << it }
8 |
9 | install {
10 | repositories.mavenInstaller {
11 | customizePom(pom, project)
12 | }
13 | }
14 |
15 | def customizePom(pom, gradleProject) {
16 | pom.whenConfigured { generatedPom ->
17 | // respect 'optional' and 'provided' dependencies
18 | gradleProject.optionalDeps.each { dep ->
19 | generatedPom.dependencies.find { it.artifactId == dep.name }?.optional = true
20 | }
21 | gradleProject.providedDeps.each { dep ->
22 | generatedPom.dependencies.find { it.artifactId == dep.name }?.scope = 'provided'
23 | }
24 |
25 | // eliminate test-scoped dependencies (no need in maven central poms)
26 | generatedPom.dependencies.removeAll { dep ->
27 | dep.scope == 'test'
28 | }
29 |
30 | // add all items necessary for maven central publication
31 | generatedPom.project {
32 | name = gradleProject.description
33 | description = gradleProject.description
34 | url = 'https://github.com/rwinch/spring-test-htmlunit'
35 | licenses {
36 | license {
37 | name 'The Apache Software License, Version 2.0'
38 | url 'https://www.apache.org/licenses/LICENSE-2.0.txt'
39 | distribution 'repo'
40 | }
41 | }
42 | scm {
43 | url = 'https://github.com/spring-projects/spring-test-htmlunit'
44 | connection = 'scm:git:git://github.com/spring-projects/spring-test-htmlunit'
45 | developerConnection = 'scm:git:git://github.com/spring-projects/spring-test-htmlunit'
46 | }
47 | developers {
48 | developer {
49 | id = 'rwinch'
50 | name = 'Rob Winch'
51 | email = 'rwinch@pivotal.com'
52 | }
53 | }
54 | }
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/mail-webapp/src/test/groovy/sample/geb/CreateMessagesISpec.groovy:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 | package sample.geb
14 |
15 | import geb.Page
16 | import geb.spock.GebReportingSpec
17 | import org.springframework.beans.factory.annotation.Autowired
18 | import org.springframework.test.web.geb.pages.*
19 | import sample.geb.pages.CreateMessagePage
20 | import sample.geb.pages.LoginPage
21 | import sample.geb.pages.ViewMessagePage
22 | import spock.lang.Stepwise
23 |
24 | /**
25 | *
26 | * @author Rob Winch
27 | *
28 | */
29 | @Stepwise
30 | class CreateMessagesISpec extends GebReportingSpec {
31 |
32 | def 'login success'() {
33 | setup:
34 | to LoginPage
35 | when:
36 | login()
37 | to CreateMessagePage
38 | then:
39 | at CreateMessagePage
40 | }
41 |
42 | def 'missing field with javascript validation displays error'() {
43 | setup:
44 | to CreateMessagePage
45 | at CreateMessagePage
46 | when:
47 | submit.click(CreateMessagePage)
48 | then:
49 | errors.contains('This field is required.')
50 | }
51 |
52 | def 'missing field server side validation displays error'() {
53 | setup:
54 | to CreateMessagePage
55 | at CreateMessagePage
56 | when:
57 | form.summary = 'Summary'
58 | submit.click(CreateMessagePage)
59 | then:
60 | errors.contains('Message is required.')
61 | }
62 |
63 | def 'successfully create new message'() {
64 | setup:
65 | def expectedSummary = 'Spring Rocks'
66 | def expectedMessage = 'In case you didn\'t know, Spring Rocks!'
67 | to CreateMessagePage
68 | at CreateMessagePage
69 | when:
70 | form.summary = expectedSummary
71 | form.text = expectedMessage
72 | submit.click(ViewMessagePage)
73 | then:
74 | at ViewMessagePage
75 | success == 'Successfully created a new message'
76 | id
77 | date
78 | summary == expectedSummary
79 | message == expectedMessage
80 | }
81 | }
--------------------------------------------------------------------------------
/mail-webapp/src/test/java/sample/webdriver/pages/ViewMessagePage.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 | package sample.webdriver.pages;
14 |
15 | import org.openqa.selenium.WebDriver;
16 | import org.openqa.selenium.WebElement;
17 | import org.openqa.selenium.support.FindBy;
18 | import sample.data.Message;
19 |
20 | import java.text.DateFormat;
21 | import java.text.ParseException;
22 | import java.util.Calendar;
23 | import java.util.Locale;
24 |
25 | /**
26 | * Represents the page where the {@link Message} details can be viewed.
27 | *
28 | * @author Rob Winch
29 | *
30 | */
31 | public class ViewMessagePage extends AbstractPage {
32 | @FindBy(className = "alert-success")
33 | private WebElement success;
34 |
35 | private WebElement id;
36 |
37 | private WebElement created;
38 |
39 | private WebElement summary;
40 |
41 | private WebElement text;
42 |
43 | public ViewMessagePage(WebDriver driver) {
44 | super(driver);
45 | }
46 |
47 | public String getSuccess() {
48 | return success.getText();
49 | }
50 |
51 | public Long getId() {
52 | return Long.parseLong(id.getText());
53 | }
54 |
55 | public Calendar getCreated() throws ParseException {
56 | Calendar result = Calendar.getInstance();
57 | DateFormat format = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, Locale.ENGLISH);
58 | result.setTime(format.parse(created.getText()));
59 | return result;
60 | }
61 |
62 | public String getSummary() {
63 | return summary.getText();
64 | }
65 |
66 | public String getText() {
67 | return text.getText();
68 | }
69 |
70 | // tag::get-message[]
71 | public Message getMessage() throws ParseException {
72 | Message message = new Message();
73 | message.setId(getId());
74 | message.setCreated(getCreated());
75 | message.setSummary(getSummary());
76 | message.setText(getText());
77 | return message;
78 | }
79 | // end::get-message[]
80 | }
81 |
--------------------------------------------------------------------------------
/mail-webapp/src/test/java/sample/config/MockDataConfig.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2002-2013 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5 | * use this file except in compliance with the License. You may obtain a copy of
6 | * the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations under
14 | * the License.
15 | */
16 | package sample.config;
17 |
18 | import static org.mockito.Matchers.any;
19 | import static org.mockito.Matchers.anyLong;
20 | import static org.mockito.Mockito.mock;
21 | import static org.mockito.Mockito.when;
22 |
23 | import java.util.Calendar;
24 | import java.util.Locale;
25 |
26 | import org.mockito.invocation.InvocationOnMock;
27 | import org.mockito.stubbing.Answer;
28 | import org.springframework.context.annotation.Bean;
29 | import org.springframework.context.annotation.Configuration;
30 |
31 | import sample.data.Message;
32 | import sample.data.MessageRepository;
33 |
34 | /**
35 | * @author Rob Winch
36 | */
37 | @Configuration
38 | public class MockDataConfig {
39 |
40 | @Bean
41 | public MessageRepository messageRepository() {
42 | final Message message = createMessage();
43 | MessageRepository messages = mock(MessageRepository.class);
44 | when(messages.save(any(Message.class))).thenAnswer(new Answer() {
45 | @Override
46 | public Message answer(InvocationOnMock invocation) throws Throwable {
47 | Object[] args = invocation.getArguments();
48 | Message result = (Message) args[0];
49 | result.setId(message.getId());
50 | result.setCreated(message.getCreated());
51 | return result;
52 | }
53 | });
54 | when(messages.findOne(anyLong())).thenReturn(message);
55 | return messages;
56 | }
57 |
58 | @Bean
59 | public Message createMessage() {
60 | Calendar created = Calendar.getInstance(Locale.ENGLISH);
61 | // we need to clear out the milliseconds since we are not interested in being that precise
62 | created.set(Calendar.MILLISECOND, 0);
63 | created.getTime().setTime(1397672456000L);
64 | Message message = new Message();
65 | message.setCreated(created);
66 | message.setId(123L);
67 | message.setSummary("Spring Rocks");
68 | message.setText("In case you didn't know, Spring Rocks!");
69 | return message;
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/mail-webapp/src/main/java/sample/config/DataConfig.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2002-2013 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5 | * use this file except in compliance with the License. You may obtain a copy of
6 | * the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations under
14 | * the License.
15 | */
16 | package sample.config;
17 |
18 | import javax.sql.DataSource;
19 |
20 | import org.springframework.context.annotation.Bean;
21 | import org.springframework.context.annotation.Configuration;
22 | import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
23 | import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
24 | import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
25 | import org.springframework.orm.jpa.JpaTransactionManager;
26 | import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
27 | import org.springframework.orm.jpa.vendor.Database;
28 | import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
29 | import sample.data.Message;
30 | import org.springframework.transaction.PlatformTransactionManager;
31 | import sample.data.MessageRepository;
32 |
33 |
34 | @Configuration
35 | @EnableJpaRepositories(basePackageClasses = MessageRepository.class)
36 | public class DataConfig {
37 |
38 | @Bean
39 | public DataSource dataSource() {
40 | EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
41 | return builder.setType(EmbeddedDatabaseType.HSQL).build();
42 | }
43 |
44 | @Bean
45 | public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
46 | HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
47 | vendorAdapter.setDatabase(Database.HSQL);
48 | vendorAdapter.setGenerateDdl(true);
49 |
50 | LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
51 | factory.setJpaVendorAdapter(vendorAdapter);
52 | factory.setPackagesToScan(Message.class.getPackage().getName());
53 | factory.setDataSource(dataSource());
54 |
55 | return factory;
56 | }
57 |
58 | @Bean
59 | public PlatformTransactionManager transactionManager() {
60 | JpaTransactionManager txManager = new JpaTransactionManager();
61 | txManager.setEntityManagerFactory(entityManagerFactory().getObject());
62 | return txManager;
63 | }
64 | }
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/mail-webapp/src/main/java/sample/mvc/MessageController.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 | package sample.mvc;
14 |
15 | import javax.validation.Valid;
16 |
17 | import org.springframework.beans.factory.annotation.Autowired;
18 | import org.springframework.stereotype.Controller;
19 | import sample.data.Message;
20 | import sample.data.MessageRepository;
21 | import org.springframework.validation.BindingResult;
22 | import org.springframework.web.bind.annotation.ModelAttribute;
23 | import org.springframework.web.bind.annotation.PathVariable;
24 | import org.springframework.web.bind.annotation.RequestMapping;
25 | import org.springframework.web.bind.annotation.RequestMethod;
26 | import org.springframework.web.servlet.ModelAndView;
27 | import org.springframework.web.servlet.mvc.support.RedirectAttributes;
28 |
29 | /**
30 | *
31 | * @author Rob Winch
32 | *
33 | */
34 | @Controller
35 | @RequestMapping("/messages/")
36 | public class MessageController {
37 | private MessageRepository messageRepository;
38 |
39 | @Autowired
40 | public MessageController(MessageRepository messageRepository) {
41 | this.messageRepository = messageRepository;
42 | }
43 |
44 | @RequestMapping
45 | public ModelAndView list() {
46 | Iterable messages = messageRepository.findAll();
47 | return new ModelAndView("messages/list", "messages", messages);
48 | }
49 |
50 | @RequestMapping("{id}")
51 | public ModelAndView view(@PathVariable("id")
52 | Long id) {
53 | Message message = messageRepository.findOne(id);
54 | return new ModelAndView("messages/view", "message", message);
55 | }
56 |
57 | @RequestMapping(value = "form", method = RequestMethod.GET)
58 | public String createForm(@ModelAttribute
59 | Message message) {
60 | return "messages/form";
61 | }
62 |
63 | @RequestMapping(method = RequestMethod.POST)
64 | public ModelAndView create(@Valid
65 | Message message, BindingResult result, RedirectAttributes redirect) {
66 | if (result.hasErrors()) {
67 | return new ModelAndView("messages/form");
68 | }
69 | message = messageRepository.save(message);
70 | redirect.addFlashAttribute("globalMessage", "Successfully created a new message");
71 | return new ModelAndView("redirect:/messages/{message.id}", "message.id", message.getId());
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/spring-test-htmlunit/src/test/java/org/springframework/test/web/servlet/htmlunit/matchers/HostRequestMatcherTests.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2002-2015 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5 | * use this file except in compliance with the License. You may obtain a copy of
6 | * the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations under
14 | * the License.
15 | */
16 | package org.springframework.test.web.servlet.htmlunit.matchers;
17 |
18 | import java.net.URL;
19 |
20 | import com.gargoylesoftware.htmlunit.WebRequest;
21 | import static org.fest.assertions.Assertions.assertThat;
22 | import org.junit.Test;
23 |
24 | /**
25 | * @author Rob Winch
26 | */
27 | public class HostRequestMatcherTests {
28 |
29 | @Test
30 | public void localhostMatches() throws Exception {
31 | WebRequestMatcher matcher = new HostRequestMatcher("localhost");
32 |
33 | boolean matches = matcher.matches(new WebRequest(new URL("http://localhost/jquery-1.11.0.min.js")));
34 | assertThat(matches).isTrue();
35 |
36 | matches = matcher.matches(new WebRequest(new URL("http://example.com/jquery-1.11.0.min.js")));
37 | assertThat(matches).isFalse();
38 | }
39 |
40 | @Test
41 | public void multipleHosts() throws Exception {
42 | WebRequestMatcher matcher = new HostRequestMatcher("localhost","example.com");
43 |
44 | boolean matches = matcher.matches(new WebRequest(new URL("http://localhost/jquery-1.11.0.min.js")));
45 | assertThat(matches).isTrue();
46 |
47 | matches = matcher.matches(new WebRequest(new URL("http://example.com/jquery-1.11.0.min.js")));
48 | assertThat(matches).isTrue();
49 | }
50 |
51 | @Test
52 | public void specificPort() throws Exception {
53 | WebRequestMatcher matcher = new HostRequestMatcher("localhost:8080");
54 |
55 | boolean matches = matcher.matches(new WebRequest(new URL("http://localhost:8080/jquery-1.11.0.min.js")));
56 | assertThat(matches).isTrue();
57 |
58 | matches = matcher.matches(new WebRequest(new URL("http://localhost:9090/jquery-1.11.0.min.js")));
59 | assertThat(matches).isFalse();
60 | }
61 |
62 | @Test
63 | public void defaultPortInMatcher() throws Exception {
64 | WebRequestMatcher matcher = new HostRequestMatcher("localhost:80");
65 |
66 | boolean matches = matcher.matches(new WebRequest(new URL("http://localhost:80/jquery-1.11.0.min.js")));
67 | assertThat(matches).isTrue();
68 |
69 | matches = matcher.matches(new WebRequest(new URL("http://localhost/jquery-1.11.0.min.js")));
70 | assertThat(matches).isTrue();
71 |
72 | matches = matcher.matches(new WebRequest(new URL("http://localhost:9090/jquery-1.11.0.min.js")));
73 | assertThat(matches).isFalse();
74 | }
75 | }
--------------------------------------------------------------------------------
/spring-test-htmlunit/src/test/java/org/springframework/test/web/servlet/htmlunit/MockMvcWebConnectionTests.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2002-2014 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5 | * use this file except in compliance with the License. You may obtain a copy of
6 | * the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations under
14 | * the License.
15 | */
16 | package org.springframework.test.web.servlet.htmlunit;
17 |
18 | import com.gargoylesoftware.htmlunit.Page;
19 | import com.gargoylesoftware.htmlunit.WebClient;
20 | import org.junit.Before;
21 | import org.junit.Test;
22 | import org.springframework.test.web.servlet.MockMvc;
23 | import org.springframework.test.web.servlet.setup.MockMvcBuilders;
24 |
25 | import java.io.IOException;
26 |
27 | import static org.fest.assertions.Assertions.assertThat;
28 |
29 | /**
30 | * @author Rob Winch
31 | */
32 | public class MockMvcWebConnectionTests {
33 | MockMvc mockMvc;
34 |
35 | WebClient webClient;
36 |
37 | @Before
38 | public void setup() {
39 | mockMvc = MockMvcBuilders
40 | .standaloneSetup(new HelloController(), new ForwardController())
41 | .build();
42 |
43 | webClient = new WebClient();
44 | }
45 |
46 | @Test
47 | public void contextPathNull() throws IOException {
48 | webClient.setWebConnection(new MockMvcWebConnection(mockMvc, null));
49 |
50 | Page page = webClient.getPage("http://localhost/context/a");
51 |
52 | assertThat(page.getWebResponse().getStatusCode()).isEqualTo(200);
53 | }
54 |
55 | @Test
56 | public void contextPathExplicit() throws IOException {
57 | webClient.setWebConnection(new MockMvcWebConnection(mockMvc, "/context"));
58 |
59 | Page page = webClient.getPage("http://localhost/context/a");
60 |
61 | assertThat(page.getWebResponse().getStatusCode()).isEqualTo(200);
62 | }
63 |
64 | @Test
65 | public void contextPathEmpty() throws IOException {
66 | webClient.setWebConnection(new MockMvcWebConnection(mockMvc, ""));
67 |
68 | Page page = webClient.getPage("http://localhost/context/a");
69 |
70 | assertThat(page.getWebResponse().getStatusCode()).isEqualTo(200);
71 | }
72 |
73 | @Test
74 | public void forward() throws IOException {
75 | webClient.setWebConnection(new MockMvcWebConnection(mockMvc, ""));
76 |
77 | Page page = webClient.getPage("http://localhost/forward");
78 |
79 | assertThat(page.getWebResponse().getContentAsString()).isEqualTo("hello");
80 | }
81 |
82 | @Test(expected = IllegalArgumentException.class)
83 | public void contextPathDoesNotStartWithSlash() throws IOException {
84 | new MockMvcWebConnection(mockMvc, "context");
85 | }
86 |
87 | @Test(expected = IllegalArgumentException.class)
88 | public void contextPathEndsWithSlash() throws IOException {
89 | new MockMvcWebConnection(mockMvc, "/context/");
90 | }
91 | }
--------------------------------------------------------------------------------
/mail-webapp/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'groovy'
2 | apply plugin: 'war'
3 | apply plugin: 'com.bmuschko.tomcat'
4 |
5 | tasks.findByPath("artifactoryPublish")?.enabled = false
6 | sonarRunner {
7 | skipProject = true
8 | }
9 |
10 | task integrationTomcatRunWar(type: com.bmuschko.gradle.tomcat.tasks.TomcatRun, dependsOn: war) {
11 | contextPath = ''
12 | daemon = true
13 | doFirst {
14 | // delay reserving ports to ensure they are still available
15 | def ports = reservePorts(3)
16 | httpPort = ports[0]
17 | ajpPort = ports[1]
18 | stopPort = ports[2]
19 | }
20 | }
21 |
22 | task integrationTomcatStop(type: com.bmuschko.gradle.tomcat.tasks.TomcatStop, dependsOn: war) {
23 | doFirst {
24 | stopPort = integrationTomcatRunWar.stopPort
25 | }
26 | }
27 |
28 | test {
29 | doFirst {
30 | def host = 'localhost:' + integrationTomcatRunWar.httpPort
31 | systemProperties['geb.build.baseUrl'] = 'http://' + host + integrationTomcatRunWar.contextPath + '/'
32 | systemProperties['geb.build.reportsDir'] = 'build/geb-reports'
33 | }
34 | }
35 |
36 | description = 'Spring MVC Test HtmlUnit Sample'
37 |
38 | tasks.findByPath("artifactoryPublish")?.enabled = false
39 |
40 | dependencies {
41 | def tomcatVersion = '7.0.61'
42 | tomcat "org.apache.tomcat.embed:tomcat-embed-core:${tomcatVersion}",
43 | "org.apache.tomcat.embed:tomcat-embed-logging-juli:${tomcatVersion}"
44 | tomcat("org.apache.tomcat.embed:tomcat-embed-jasper:${tomcatVersion}")
45 |
46 | compile "org.springframework:spring-context:$springVersion",
47 | "org.springframework:spring-webmvc:$springVersion",
48 | "org.springframework.data:spring-data-jpa:1.5.1.RELEASE",
49 | "org.hibernate.javax.persistence:hibernate-jpa-2.0-api:1.0.1.Final",
50 | "org.hibernate:hibernate-entitymanager:4.3.4.Final",
51 | "org.hibernate:hibernate-validator:4.1.0.Final",
52 | "org.aspectj:aspectjrt:1.6.10",
53 | "javax.validation:validation-api:1.0.0.GA",
54 | "org.slf4j:slf4j-log4j12:$slf4jVersion",
55 | "org.slf4j:jcl-over-slf4j:$slf4jVersion",
56 | "org.hsqldb:hsqldb:2.3.2",
57 | "org.thymeleaf:thymeleaf:2.1.2.RELEASE",
58 | "org.thymeleaf:thymeleaf-spring4:2.1.2.RELEASE",
59 | "org.springframework.security:spring-security-web:$springSecurityVersion",
60 | "org.springframework.security:spring-security-config:$springSecurityVersion"
61 |
62 | providedCompile "javax.servlet:javax.servlet-api:$servletApiVersion"
63 |
64 | testCompile project(':spring-test-htmlunit'),
65 | "org.springframework:spring-test:$springVersion",
66 | "org.seleniumhq.selenium:selenium-htmlunit-driver:$seleniumVersion",
67 | "org.seleniumhq.selenium:selenium-support:$seleniumVersion",
68 | "org.gebish:geb-spock:$gebVersion",
69 | "org.spockframework:spock-core:$spockVersion",
70 | "org.spockframework:spock-spring:$spockVersion",
71 | "junit:junit:$junitVersion",
72 | 'org.easytesting:fest-assert-core:2.0M10',
73 | "org.mockito:mockito-all:$mockitoVersion",
74 | "org.codehaus.groovy:groovy:2.4.3",
75 | 'org.easytesting:fest-assert:1.4',
76 | "org.springframework.security:spring-security-test:$springSecurityVersion"
77 |
78 | jacoco "org.jacoco:org.jacoco.agent:$jacocoVersion:runtime"
79 | }
80 |
81 | eclipse.wtp.component.contextPath = ''
82 |
83 | test {
84 | dependsOn integrationTomcatRunWar
85 | finalizedBy integrationTomcatStop
86 | }
--------------------------------------------------------------------------------
/src/test/java/docs/htmlunit/HtmlUnitDocTests.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2002-2015 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5 | * use this file except in compliance with the License. You may obtain a copy of
6 | * the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations under
14 | * the License.
15 | */
16 | package docs.htmlunit;
17 |
18 | import com.gargoylesoftware.htmlunit.WebClient;
19 | import org.junit.Test;
20 | import org.junit.runner.RunWith;
21 | import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
22 |
23 | import org.springframework.beans.factory.annotation.Autowired;
24 | import org.springframework.context.annotation.Configuration;
25 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
26 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
27 | import org.springframework.test.context.ContextConfiguration;
28 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
29 | import org.springframework.test.context.web.WebAppConfiguration;
30 | import org.springframework.test.web.servlet.MockMvc;
31 | import org.springframework.test.web.servlet.htmlunit.MockMvcWebClientBuilder;
32 | import org.springframework.test.web.servlet.htmlunit.MockMvcWebConnection;
33 | import org.springframework.test.web.servlet.setup.MockMvcBuilders;
34 | import org.springframework.web.context.WebApplicationContext;
35 | import org.springframework.web.servlet.config.annotation.EnableWebMvc;
36 |
37 | /**
38 | * @author Rob Winch
39 | */
40 | @RunWith(SpringJUnit4ClassRunner.class)
41 | @ContextConfiguration
42 | @WebAppConfiguration
43 | public class HtmlUnitDocTests {
44 | @Autowired
45 | WebApplicationContext context;
46 |
47 | WebClient webClient;
48 |
49 | @Test
50 | public void webclientWithMockMvc() {
51 | // tag::webclient-mockmvc[]
52 | MockMvc mockMvc = MockMvcBuilders
53 | .webAppContextSetup(context)
54 | .apply(springSecurity())
55 | .build();
56 |
57 | webClient = MockMvcWebClientBuilder
58 | .mockMvcSetup(mockMvc)
59 | // for illustration only - defaults to ""
60 | .contextPath("")
61 | .createWebClient();
62 | // end::webclient-mockmvc[]
63 | }
64 |
65 | @Test
66 | public void webclientVerbose() {
67 | // tag::webclient-verbose[]
68 | String contextPath = "";
69 | MockMvc mockMvc = MockMvcBuilders
70 | .webAppContextSetup(context)
71 | .apply(springSecurity())
72 | .build();
73 |
74 | webClient = new WebClient();
75 | webClient.setWebConnection(new MockMvcWebConnection(mockMvc, contextPath));
76 | // end::webclient-verbose[]
77 | }
78 |
79 | @Configuration
80 | @EnableWebMvc
81 | @EnableWebSecurity
82 | static class Config {
83 | @Autowired
84 | public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
85 | auth
86 | .inMemoryAuthentication();
87 | }
88 | }
89 | }
90 |
--------------------------------------------------------------------------------
/spring-test-htmlunit/src/main/java/org/springframework/test/web/servlet/htmlunit/matchers/HostRequestMatcher.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2002-2015 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5 | * use this file except in compliance with the License. You may obtain a copy of
6 | * the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations under
14 | * the License.
15 | */
16 | package org.springframework.test.web.servlet.htmlunit.matchers;
17 |
18 | import java.net.URL;
19 | import java.util.Arrays;
20 | import java.util.HashSet;
21 | import java.util.Set;
22 | import java.util.regex.Pattern;
23 |
24 | import com.gargoylesoftware.htmlunit.WebRequest;
25 |
26 | /**
27 | *
28 | * An implementation of WebRequestMatcher that allows matching on the host and optionally
29 | * the port of WebRequest#getUrl(). For example, the following would match any request to
30 | * the host "code.jquery.com" without regard for the port:
31 | *
36 | *
37 | * Multiple hosts can also be passed in. For example, the following would match an request
38 | * to the host "code.jquery.com" or the host "cdn.com" without regard for the port:
39 | *
40 | *
45 | * Alternatively, one can also specify the port. For example, the following would match
46 | * any request to the host "code.jquery.com" with the port of 80.
47 | *
54 | * The above cdnMatcher would match: "http://code.jquery.com/jquery.js" (default port of
55 | * 80) and "http://code.jquery.com:80/jquery.js". However, it would not match
56 | * "https://code.jquery.com/jquery.js" (default port of 443).
57 | *
58 | *
59 | * @author Rob Winch
60 | * @see org.springframework.test.web.servlet.htmlunit.matchers.UrlRegexRequestMatcher
61 | * @see org.springframework.test.web.servlet.htmlunit.DelegatingWebConnection
62 | */
63 | public final class HostRequestMatcher implements WebRequestMatcher {
64 | private final Set hosts = new HashSet();
65 |
66 | /**
67 | * Creates a new instance
68 | *
69 | * @param hosts the hosts to match on (i.e. "localhost", "example.com:443")
70 | */
71 | public HostRequestMatcher(String... hosts) {
72 | this.hosts.addAll(Arrays.asList(hosts));
73 | }
74 |
75 | @Override
76 | public boolean matches(WebRequest request) {
77 | URL url = request.getUrl();
78 | String host = url.getHost();
79 |
80 | if(hosts.contains(host)) {
81 | return true;
82 | }
83 |
84 | int port = url.getPort();
85 | if(port == -1) {
86 | port = url.getDefaultPort();
87 | }
88 | String hostAndPort = host + ":" + port;
89 |
90 | return hosts.contains(hostAndPort);
91 | }
92 | }
93 |
--------------------------------------------------------------------------------
/src/test/java/docs/webdriver/WebDriverDocTests.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2002-2015 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5 | * use this file except in compliance with the License. You may obtain a copy of
6 | * the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations under
14 | * the License.
15 | */
16 | package docs.webdriver;
17 |
18 | import org.junit.Test;
19 | import org.junit.runner.RunWith;
20 | import org.openqa.selenium.WebDriver;
21 | import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
22 |
23 | import org.springframework.beans.factory.annotation.Autowired;
24 | import org.springframework.context.annotation.Configuration;
25 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
26 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
27 | import org.springframework.test.context.ContextConfiguration;
28 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
29 | import org.springframework.test.context.web.WebAppConfiguration;
30 | import org.springframework.test.web.servlet.MockMvc;
31 | import org.springframework.test.web.servlet.htmlunit.MockMvcWebConnection;
32 | import org.springframework.test.web.servlet.htmlunit.webdriver.MockMvcHtmlUnitDriverBuilder;
33 | import org.springframework.test.web.servlet.htmlunit.webdriver.WebConnectionHtmlUnitDriver;
34 | import org.springframework.test.web.servlet.setup.MockMvcBuilders;
35 | import org.springframework.web.context.WebApplicationContext;
36 | import org.springframework.web.servlet.config.annotation.EnableWebMvc;
37 |
38 | /**
39 | * @author Rob Winch
40 | */
41 | @RunWith(SpringJUnit4ClassRunner.class)
42 | @ContextConfiguration
43 | @WebAppConfiguration
44 | public class WebDriverDocTests {
45 | @Autowired
46 | WebApplicationContext context;
47 |
48 | WebDriver driver;
49 |
50 | @Test
51 | public void webDriverWithMockMvc() {
52 | // tag::webdriver-mockmvc[]
53 | MockMvc mockMvc = MockMvcBuilders
54 | .webAppContextSetup(context)
55 | .apply(springSecurity())
56 | .build();
57 |
58 | driver = MockMvcHtmlUnitDriverBuilder
59 | .mockMvcSetup(mockMvc)
60 | // for illustration only - defaults to ""
61 | .contextPath("")
62 | .createDriver();
63 | // end::webdriver-mockmvc[]
64 | }
65 |
66 | @Test
67 | public void webDriverVerbose() {
68 | // tag::webdriver-verbose[]
69 | String contextPath = "";
70 | MockMvc mockMvc = MockMvcBuilders
71 | .webAppContextSetup(context)
72 | .apply(springSecurity())
73 | .build();
74 |
75 | WebConnectionHtmlUnitDriver driver = new WebConnectionHtmlUnitDriver();
76 | driver.setWebConnection(new MockMvcWebConnection(mockMvc, contextPath));
77 | // end::webdriver-verbose[]
78 | }
79 |
80 | @Configuration
81 | @EnableWebMvc
82 | @EnableWebSecurity
83 | static class Config {
84 | @Autowired
85 | public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
86 | auth
87 | .inMemoryAuthentication();
88 | }
89 | }
90 | }
91 |
--------------------------------------------------------------------------------
/mail-webapp/src/main/java/sample/config/WebMvcConfig.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2002-2013 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5 | * use this file except in compliance with the License. You may obtain a copy of
6 | * the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations under
14 | * the License.
15 | */
16 | package sample.config;
17 |
18 | import org.springframework.beans.factory.annotation.Autowired;
19 | import org.springframework.context.annotation.Bean;
20 | import org.springframework.context.annotation.ComponentScan;
21 | import org.springframework.core.Ordered;
22 | import org.springframework.data.repository.support.DomainClassConverter;
23 | import org.springframework.format.support.FormattingConversionService;
24 | import org.springframework.web.servlet.config.annotation.EnableWebMvc;
25 | import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
26 | import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
27 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
28 | import org.thymeleaf.spring4.SpringTemplateEngine;
29 | import org.thymeleaf.spring4.view.ThymeleafViewResolver;
30 | import org.thymeleaf.templateresolver.ServletContextTemplateResolver;
31 | import org.thymeleaf.templateresolver.TemplateResolver;
32 | import sample.mvc.MessageController;
33 |
34 | @EnableWebMvc
35 | @ComponentScan(basePackageClasses = MessageController.class)
36 | public class WebMvcConfig extends WebMvcConfigurerAdapter {
37 |
38 | @Autowired
39 | private FormattingConversionService mvcConversionService;
40 |
41 | @Override
42 | public void addViewControllers(ViewControllerRegistry registry) {
43 | registry.addViewController("/login").setViewName("login");
44 | registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
45 | }
46 |
47 | @Override
48 | public void addResourceHandlers(ResourceHandlerRegistry registry) {
49 | registry
50 | .addResourceHandler("/resources/**")
51 | .addResourceLocations("/resources/")
52 | .setCachePeriod(31556926);
53 | registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
54 | }
55 |
56 | @Bean
57 | public TemplateResolver templateResolver() {
58 | TemplateResolver result = new ServletContextTemplateResolver();
59 | result.setPrefix("/WEB-INF/templates/");
60 | result.setSuffix(".html");
61 | result.setTemplateMode("HTML5");
62 | return result;
63 | }
64 |
65 | @Bean
66 | public SpringTemplateEngine templateEngine(TemplateResolver templateResolver) {
67 | SpringTemplateEngine templateEngine = new SpringTemplateEngine();
68 | templateEngine.setTemplateResolver(templateResolver);
69 | return templateEngine;
70 | }
71 |
72 | @Bean
73 | public ThymeleafViewResolver viewResolver(SpringTemplateEngine templateEngine) {
74 | ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
75 | viewResolver.setTemplateEngine(templateEngine);
76 | return viewResolver;
77 | }
78 |
79 | @Bean
80 | public DomainClassConverter> domainClassConverter() {
81 | return new DomainClassConverter(mvcConversionService);
82 | }
83 | }
--------------------------------------------------------------------------------
/spring-test-htmlunit/src/main/java/org/springframework/test/web/servlet/htmlunit/webdriver/WebConnectionHtmlUnitDriver.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2002-2015 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5 | * use this file except in compliance with the License. You may obtain a copy of
6 | * the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 | * License for the specific language governing permissions and limitations under
14 | * the License.
15 | */
16 | package org.springframework.test.web.servlet.htmlunit.webdriver;
17 |
18 | import com.gargoylesoftware.htmlunit.BrowserVersion;
19 | import com.gargoylesoftware.htmlunit.WebClient;
20 | import com.gargoylesoftware.htmlunit.WebConnection;
21 | import org.openqa.selenium.Capabilities;
22 | import org.openqa.selenium.htmlunit.HtmlUnitDriver;
23 | import org.springframework.test.web.servlet.MockMvc;
24 | import org.springframework.test.web.servlet.htmlunit.MockMvcWebConnection;
25 | import org.springframework.test.web.servlet.setup.MockMvcBuilders;
26 | import org.springframework.util.Assert;
27 | import org.springframework.web.context.WebApplicationContext;
28 |
29 | /**
30 | *
31 | * Allows configuring the WebConnection for an HtmlUnitDriver instance. This is useful
32 | * because it allows a MockMvcWebConnection to be injected.
33 | *
34 | *
35 | * @author Rob Winch
36 | * @since 1.0
37 | * @see MockMvcHtmlUnitDriverBuilder
38 | */
39 | public class WebConnectionHtmlUnitDriver extends HtmlUnitDriver {
40 | private WebClient webClient;
41 |
42 | public WebConnectionHtmlUnitDriver(BrowserVersion version) {
43 | super(version);
44 | }
45 |
46 | public WebConnectionHtmlUnitDriver() {
47 | }
48 |
49 | public WebConnectionHtmlUnitDriver(boolean enableJavascript) {
50 | super(enableJavascript);
51 | }
52 |
53 | public WebConnectionHtmlUnitDriver(Capabilities capabilities) {
54 | super(capabilities);
55 | }
56 |
57 | /**
58 | * Captures the WebClient that is used so that its WebConnection is accessible.
59 | *
60 | * @param client The client to modify
61 | * @return The modified client
62 | */
63 | @Override
64 | protected final WebClient modifyWebClient(WebClient client) {
65 | webClient = super.modifyWebClient(client);
66 | webClient = configureWebClient(webClient);
67 | return webClient;
68 | }
69 |
70 | /**
71 | * Subclasses can override this method to customise the WebClient that the HtmlUnit
72 | * driver uses.
73 | *
74 | * @param client The client to modify
75 | * @return The modified client
76 | */
77 | protected WebClient configureWebClient(WebClient client) {
78 | return client;
79 | }
80 |
81 | /**
82 | * Allows accessing the current WebConnection
83 | *
84 | * @return the current WebConnection
85 | */
86 | public WebConnection getWebConnection() {
87 | return webClient.getWebConnection();
88 | }
89 |
90 | /**
91 | * Sets the WebConnection to be used.
92 | *
93 | * @param webConnection the WebConnection to use. Cannot be null.
94 | */
95 | public void setWebConnection(WebConnection webConnection) {
96 | Assert.notNull(webConnection, "webConnection cannot be null");
97 | this.webClient.setWebConnection(webConnection);
98 | }
99 | }
--------------------------------------------------------------------------------
/mail-webapp/src/test/java/sample/webdriver/WebDriverCreateMessageITests.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5 | * the License. You may obtain a copy of the License at
6 | *
7 | * http://www.apache.org/licenses/LICENSE-2.0
8 | *
9 | * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10 | * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 | * specific language governing permissions and limitations under the License.
12 | */
13 | package sample.webdriver;
14 |
15 | import org.junit.After;
16 | import org.junit.Before;
17 | import org.junit.Test;
18 | import org.openqa.selenium.WebDriver;
19 | import org.openqa.selenium.htmlunit.HtmlUnitDriver;
20 | import org.springframework.beans.factory.annotation.Autowired;
21 | import org.springframework.web.context.WebApplicationContext;
22 | import sample.config.MockDataConfig;
23 | import sample.data.Message;
24 | import sample.webdriver.pages.CreateMessagePage;
25 | import sample.webdriver.pages.LoginPage;
26 | import sample.webdriver.pages.ViewMessagePage;
27 |
28 | import java.text.ParseException;
29 |
30 | import static sample.fest.Assertions.assertThat;
31 |
32 | /**
33 | *
34 | * An integration test that validates the {@link CreateMessagePage}. Notice that we are able to reuse the same page
35 | * objects as the {@link MockMvcHtmlUnitDriverCreateMessageTests}.
36 | *
37 | *
38 | * NOTE The web application must actually be running for this test to pass.
39 | *
40 | *
41 | * @author Rob Winch
42 | * @see MockMvcHtmlUnitDriverCreateMessageTests
43 | */
44 | public class WebDriverCreateMessageITests {
45 | private Message expectedMessage = new MockDataConfig().createMessage();
46 |
47 | @Autowired
48 | private WebApplicationContext context;
49 |
50 | private WebDriver driver;
51 |
52 | @Before
53 | public void setup() {
54 | driver = new HtmlUnitDriver(true);
55 | LoginPage.login(driver);
56 | }
57 |
58 | @After
59 | public void destroy() {
60 | if(driver != null) {
61 | driver.close();
62 | }
63 | }
64 |
65 | @Test
66 | public void missingFieldWithJavascriptValidationDisplaysError() {
67 | CreateMessagePage messagePage = CreateMessagePage.to(driver);
68 | messagePage = messagePage.createMessage(CreateMessagePage.class, "", "");
69 | assertThat(messagePage.getErrors()).isEqualTo("This field is required.");
70 | }
71 |
72 | @Test
73 | public void missingFieldServerSideValidationDisplaysError() {
74 | CreateMessagePage messagePage = CreateMessagePage.to(driver);
75 | messagePage = messagePage.createMessage(CreateMessagePage.class, "Summary", "");
76 | assertThat(messagePage.getErrors()).isEqualTo("Message is required.");
77 | }
78 |
79 | @Test
80 | public void successfullyCreateMessage() throws ParseException {
81 | String expectedSummary = expectedMessage.getSummary();
82 | String expectedText = expectedMessage.getText();
83 |
84 | CreateMessagePage page = CreateMessagePage.to(driver);
85 |
86 | ViewMessagePage viewMessagePage = page.createMessage(ViewMessagePage.class, expectedSummary, expectedText);
87 | assertThat(viewMessagePage.getMessage()).isEqualToIgnoringGeneratedFields(expectedMessage);
88 | assertThat(viewMessagePage.getSuccess()).isEqualTo("Successfully created a new message");
89 | }
90 | }
91 |
--------------------------------------------------------------------------------
/spring-test-htmlunit/src/main/java/org/springframework/test/web/servlet/htmlunit/MockWebResponseBuilder.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package org.springframework.test.web.servlet.htmlunit;
17 |
18 | import java.io.IOException;
19 | import java.util.ArrayList;
20 | import java.util.Collection;
21 | import java.util.List;
22 |
23 | import org.springframework.http.HttpStatus;
24 | import org.springframework.mock.web.MockHttpServletResponse;
25 | import org.springframework.util.Assert;
26 |
27 | import com.gargoylesoftware.htmlunit.WebRequest;
28 | import com.gargoylesoftware.htmlunit.WebResponse;
29 | import com.gargoylesoftware.htmlunit.WebResponseData;
30 | import com.gargoylesoftware.htmlunit.util.NameValuePair;
31 |
32 | /**
33 | * @author Rob Winch
34 | *
35 | */
36 | final class MockWebResponseBuilder {
37 | private final long startTime;
38 |
39 | private final WebRequest webRequest;
40 |
41 | private final MockHttpServletResponse response;
42 |
43 | public MockWebResponseBuilder(long startTime, WebRequest webRequest, MockHttpServletResponse httpServletResponse) {
44 | Assert.notNull(webRequest, "webRequest");
45 | Assert.notNull(httpServletResponse, "httpServletResponse cannot be null");
46 | this.startTime = startTime;
47 | this.webRequest = webRequest;
48 | this.response = httpServletResponse;
49 | }
50 |
51 | public WebResponse build() throws IOException {
52 | WebResponseData webResponseData = webResponseData();
53 | long endTime = System.currentTimeMillis();
54 | return new WebResponse(webResponseData, webRequest, endTime - startTime);
55 | }
56 |
57 | private WebResponseData webResponseData() throws IOException {
58 | List responseHeaders = responseHeaders();
59 | int statusCode = response.getRedirectedUrl() == null ? response.getStatus() : 301;
60 | String statusMessage = statusMessage(statusCode);
61 | return new WebResponseData(response.getContentAsByteArray(), statusCode, statusMessage, responseHeaders);
62 | }
63 |
64 | private String statusMessage(int statusCode) {
65 | String errorMessage = response.getErrorMessage();
66 | if (errorMessage != null) {
67 | return errorMessage;
68 | }
69 | try {
70 | return HttpStatus.valueOf(statusCode).getReasonPhrase();
71 | }
72 | catch (IllegalArgumentException useDefault) {
73 | }
74 | ;
75 | return "N/A";
76 | }
77 |
78 | private List responseHeaders() {
79 | Collection headerNames = response.getHeaderNames();
80 | List responseHeaders = new ArrayList(headerNames.size());
81 | for (String headerName : headerNames) {
82 | List