我正在尝试使用简单的单元测试,但它会返回404状态。
Enpoints Class:
@Path("/v1")
public class Endpoints {
@Context
private HttpServletResponse servletResponse;
private void allowCrossDomainAccess() {
if (servletResponse != null){
servletResponse.setHeader("Access-Control-Allow-Origin", "*");
}
}
@GET
@Path("/whoami")
@Produces(MediaType.APPLICATION_JSON)
public String whoami(@Context final HttpServletRequest request){
allowCrossDomainAccess();
// Extract the software version from the user agent
final String userAgent = request.getHeader("user-agent");
final Pattern pattern = Pattern.compile("\\((.+?)\\)"); // Regex to extract anything between opening and closing curly bracers
final Matcher matcher = pattern.matcher(userAgent);
matcher.find();
final String software = matcher.group(1);
final String ipAddress;
if (request.getHeader("X-Forwarded-For") != null){ // Heroku adds this header
ipAddress = request.getHeader("X-Forwarded-For");
} else {
ipAddress = request.getRemoteAddr();
}
final JSONObject json = new JSONObject();
json.put("ipaddress", ipAddress);
json.put("locale", request.getLocale());
json.put("software", software);
return json.toString(4);
}
}
我的测试班:
public class EndpointsTest extends JerseyTest {
@Override
protected Application configure() {
return new ResourceConfig(Endpoints.class);
}
@Test
public void parseHeadersTest() {
Response output = target().path("/api/v1/whoami").request().get();
System.out.println("response: " + output);
assertEquals(200, output.getStatus());
}
}
输出:
Jul 15, 2016 2:30:37 PM org.glassfish.jersey.test.grizzly.GrizzlyTestContainerFactory$GrizzlyTestContainer <init>
INFO: Creating GrizzlyTestContainer configured at the base URI http://localhost:9998/
Jul 15, 2016 2:30:37 PM org.glassfish.grizzly.http.server.NetworkListener start
INFO: Started listener bound to [localhost:9998]
Jul 15, 2016 2:30:37 PM org.glassfish.grizzly.http.server.HttpServer start
INFO: [HttpServer] Started.
response: InboundJaxrsResponse{context=ClientResponse{method=GET, uri=http://localhost:9998/api/v1/whoami, status=404, reason=Not Found}}
Jul 15, 2016 2:30:37 PM org.glassfish.grizzly.http.server.NetworkListener shutdownNow
INFO: Stopped listener bound to [localhost:9998]
如您所见,resposne返回404错误。如果我通过在单元测试之外运行Main类来启动服务器并导航到响应的URI(http://localhost:9998/api/v1/whoami),那么它可以正常工作。
为什么单位测试不起作用?
修改
public class Main {
public static void main(String[] args) throws Exception{
// The port that we should run on can be set into an environment variable
// Look for that variable and default to 8080 if it isn't there.
String webPort = System.getenv("PORT");
if (webPort == null || webPort.isEmpty()) {
webPort = "9998";
}
final Server server = new Server(Integer.valueOf(webPort));
final WebAppContext root = new WebAppContext();
root.setContextPath("/");
// Parent loader priority is a class loader setting that Jetty accepts.
// By default Jetty will behave like most web containers in that it will
// allow your application to replace non-server libraries that are part of the
// container. Setting parent loader priority to true changes this behavior.
// Read more here: http://wiki.eclipse.org/Jetty/Reference/Jetty_Classloading
root.setParentLoaderPriority(true);
final String webappDirLocation = "src/main/webapp/";
root.setDescriptor(webappDirLocation + "/WEB-INF/web.xml");
root.setResourceBase(webappDirLocation);
server.setHandler(root);
server.start();
server.join();
}
}
WEB-INF / web.xml中
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<servlet>
<servlet-name>Jersey Web Application</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>org.rich.fcc</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
</web-app>