如何测试RESTful应用程序?

时间:2017-01-18 12:44:44

标签: java jax-rs jersey-test-framework

我有一个服务的应用程序示例:

RestApp.java

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("/webapi")
public class RestApp extends Application {

    @Override
    public Set<Class<?>> getClasses() {
        final Set<Class<?>> classes = new HashSet<>();
        classes.add(MessageService.class);
        return classes;
    }
}

MessageService.java

import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.net.URI;
import java.util.List;

@Stateless
@Path("/messages")
public class MessageService {

    @Inject
    private MessagesManager messagesManager;

    @GET
    @Path("all")
    @Produces({MediaType.APPLICATION_JSON})
    public List<Message> getMessages() {
        return messagesManager.getMessages();
    }
}

并且服务依赖于单例MessagesManager.java:

import javax.ejb.*;
import javax.inject.Singleton;

@Singleton
@Startup
@ConcurrencyManagement(ConcurrencyManagementType.CONTAINER)
public class MessagesManager implements Serializable {

    private List<Message> messages = new ArrayList<>();

    @Lock(LockType.READ)
    public List<Message> getMessages() {
        messages.add(new Message(1, "message text"));
        return messages;
    }
}

这个应用程序工作正常。但在测试期间发生注射错误:

  

org.glassfish.hk2.api.UnsatisfiedDependencyException:SystemInjecteeImpl没有可用于注入的对象(r​​equiredType = MessagesManager,parent = MessageService,qualifiers = {},position = -1,optional = false,self = false,unqualified = NULL,1232089028)

测试代码是:

import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.junit.Test;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.Response;
import static org.junit.Assert.assertEquals;

public class RestAppTest extends JerseyTest {

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

    @Test
    public void testGet() {
        final Response response = target("messages/all").request().get();
        assertEquals(200, response.getStatus());
    }
}

为什么会发生以及如何解决?

2 个答案:

答案 0 :(得分:1)

应用程序上下文中缺少类MessagesManager。将类添加到configure方法中:

return new ResourceConfig(MessageService.class, MessagesManager.class);

答案 1 :(得分:-1)

你需要几件事

1&GT;为REST API构建良好的JSON结构

2 - ;某种REST客户端,例如用于chrome,Mozilla等的高级REST客户端,可用作插件。 POSTMAN也是一个有用的工具