/
JettyTestCase.java
85 lines (72 loc) · 2.67 KB
/
JettyTestCase.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package org.kohsuke.stapler.test;
import com.gargoylesoftware.htmlunit.WebClient;
import junit.framework.TestCase;
import org.eclipse.jetty.http.UriCompliance;
import org.eclipse.jetty.server.HttpConfiguration;
import org.eclipse.jetty.server.HttpConnectionFactory;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.webapp.WebAppContext;
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.WebApp;
import javax.servlet.ServletContext;
import java.net.URL;
/**
* Base test case for embedded Jetty.
*
* Your test method runs with embedded Jetty with the instance of your test class bound to the root "application"
* object in Stapler. You can use {@link WebClient} to make HTTP calls, receive that on your test class,
* and inspect side-effects, etc.
*
* @author Kohsuke Kawaguchi
*/
public abstract class JettyTestCase extends TestCase {
protected Server server;
/**
* The top URL of this test web application.
*/
protected URL url;
protected Stapler stapler;
protected ServletContext servletContext;
protected WebApp webApp;
@Override
protected void setUp() throws Exception {
super.setUp();
server = new Server();
server.setHandler(new WebAppContext("/noroot", ""));
final ServletContextHandler context = new ServletContextHandler(server, getContextPath(), ServletContextHandler.SESSIONS);
configure(context);
server.setHandler(context);
ServerConnector connector = new ServerConnector(server);
HttpConfiguration hc = connector.getConnectionFactory(HttpConnectionFactory.class).getHttpConfiguration();
hc.setUriCompliance(UriCompliance.LEGACY);
server.addConnector(connector);
server.start();
url = new URL("http://localhost:"+connector.getLocalPort()+getContextPath()+"/");
servletContext = context.getServletContext();
webApp = WebApp.get(servletContext);
// export the test object as the root as a reasonable default.
webApp.setApp(this);
}
/**
* Can be used to set different context path for the root object.
*
* For example, "/foo/bar"
*/
protected String getContextPath() {
return "";
}
/**
* Sets up how the servlet/filters are bound.
*/
protected void configure(ServletContextHandler context) {
context.addServlet(new ServletHolder(new Stapler()), "/*");
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
server.stop();
}
}