Java rest服务器:进行单元测试

时间:2015-07-31 07:52:22

标签: java rest unit-testing

我尝试为独立的休息服务器进行单元测试。如果我运行其余的服务器它很好用。但我不知道如何让UnitTest运行。

我的主要课程:

public class Main {

private static final int DEFAULT_PORT = 8080;
private final int serverPort;
private final Server restServer;
public Main(final int serverPort) throws Exception {
    this.serverPort = serverPort;

    restServer = configureServer();
    restServer.start();
    restServer.join();
}

public void close() throws Exception {
    if (restServer != null) {
        restServer.stop();
    }
}

private Server configureServer() {
    ResourceConfig resourceConfig = new ResourceConfig();
    resourceConfig.packages(Main.class.getPackage().getName());
    resourceConfig.register(JacksonFeature.class);
    ServletContainer servletContainer = new ServletContainer(resourceConfig);
    ServletHolder sh = new ServletHolder(servletContainer);
    Server server = new Server(serverPort);
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");
    context.addServlet(sh, "/*");
    server.setHandler(context);
    return server;
}

public static void main(String[] args) throws Exception {
    int serverPort = DEFAULT_PORT;
    if (args.length >= 1) {
        try {
            serverPort = Integer.parseInt(args[0]);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }

    new Main(serverPort);
}

资源类:

@Path("builder")
public class ReportBuilderResource {

    @POST
    @Path("/build")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces({MediaType.TEXT_PLAIN})
    public String makeReport(final ReportDescription reportDescription) {
        return reportDescription.getName();
    }
}

我的单元测试课程:

public class ReportBuilderResourceTest extends JerseyTest {

@Override
public AppDescriptor configure() {
    return new WebAppDescriptor.Builder()
            .initParam(WebComponent.RESOURCE_CONFIG_CLASS, ClassNamesResourceConfig.class.getName())
            .initParam(ClassNamesResourceConfig.PROPERTY_CLASSNAMES, ReportBuilderResource.class.getName())
            .build();
}

@Test
public void testBuildReport() throws Exception {
    System.out.println("Test Build Report");
    ReportDescription reportDescription = new ReportDescription();

    JSONObject jsonObject = new JSONObject(reportDescription);
    resource().path("builder/").post(jsonObject.toString());
}

输出日志:

juil. 31, 2015 9:48:53 AM com.sun.jersey.test.framework.spi.container.inmemory.InMemoryTestContainerFactory$InMemoryTestContainer <init>
INFO: Creating low level InMemory test container configured at the base URI http://localhost:9998/
Running com.fdilogbox.report.serveur.ReportBuilderResourceTest
juil. 31, 2015 9:48:53 AM com.sun.jersey.test.framework.spi.container.inmemory.InMemoryTestContainerFactory$InMemoryTestContainer start
INFO: Starting low level InMemory test container
juil. 31, 2015 9:48:53 AM com.sun.jersey.server.impl.application.WebApplicationImpl _initiate
INFO: Initiating Jersey application, version 'Jersey: 1.19 02/11/2015 03:25 AM'
Test Build Report
juil. 31, 2015 9:48:54 AM com.sun.jersey.api.container.filter.LoggingFilter filter
INFO: 1 * Server in-bound request
1 > POST http://localhost:9998/builder/
1 > Content-Type: text/plain
1 > 
{"name":null,"report":null}

juil. 31, 2015 9:48:54 AM com.sun.jersey.api.container.filter.LoggingFilter$Adapter finish
INFO: 1 * Server out-bound response
1 < 405
1 < Allow: OPTIONS
1 < 

Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.497 sec <<< FAILURE! - in com.fdilogbox.report.serveur.ReportBuilderResourceTest
testBuildReport(com.fdilogbox.report.serveur.ReportBuilderResourceTest)  Time elapsed: 0.496 sec  <<< ERROR!
com.sun.jersey.api.client.UniformInterfaceException: Client response status: 405
    at com.sun.jersey.api.client.WebResource.voidHandle(WebResource.java:709)
    at com.sun.jersey.api.client.WebResource.post(WebResource.java:238)
    at com.fdilogbox.report.serveur.ReportBuilderResourceTest.testBuildReport(ReportBuilderResourceTest.java:47)

我认为服务器没有“运行”测试。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

您的资源侦听“/ builder”,但内部唯一的方法是侦听“/ builder / build”。由于没有方法监听@ post和“/ builder”,因此你得到一个Http 405 - 方法不允许。

您可以从“makeReport”方法中删除@Path(“/ build”),也可以在测试中更改resource()。path(“builder / build”)....

顺便说一下:

您只需要add one of these contatiner adapters和此代码段就可以使用Jersey 2运行单元测试:

public class ReportBuilderResourceTest extends JerseyTest {

 @Override
 protected Application configure() {
     return new ResourceConfig(ReportBuilderResource.class);
 }
...
}