generated from ohjelmointi2/embedded-tomcat-template
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTestServer.java
More file actions
74 lines (62 loc) · 2.02 KB
/
TestServer.java
File metadata and controls
74 lines (62 loc) · 2.02 KB
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
package testserver;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;
import launch.Main;
/**
* Utility class for starting and stopping an embedded Tomcat server and making
* requests to it. See IndexServletTest for example usage.
*
* @author T. Havulinna
*/
public class TestServer {
private static final int TEST_PORT = 8888;
private static final String SERVER_ROOT = "http://localhost:" + TEST_PORT;
private static Tomcat server;
private static HttpClient client = HttpClient.newHttpClient();
/**
* Creates and starts an embedded Tomcat server that can be called in JUnit
* tests.
*/
public static void start() {
try {
if (server == null) {
server = Main.createServer(TEST_PORT);
}
server.start();
} catch (LifecycleException e) {
throw new RuntimeException(e);
}
}
/**
* Stops the embedded tests. This should be called after a test suite has been
* executed.
*/
public static void stop() {
try {
server.stop();
} catch (LifecycleException e) {
throw new RuntimeException(e);
}
}
/**
* Makes a GET request to the given path in the embedded Tomcat server.
*
* @param path String such as "/" or "/todos/1.json"
* @return HttpResponse<String> containing the headers and body of the response
*/
public static HttpResponse<String> get(String path) {
URI uri = URI.create(SERVER_ROOT + path);
try {
HttpRequest request = HttpRequest.newBuilder(uri).build();
return client.send(request, BodyHandlers.ofString());
} catch (InterruptedException | IOException e) {
throw new RuntimeException(e);
}
}
}