我有一個應用程序例如用服務:如何測試RESTful應用程序?
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(requiredType = MessagesManager,父= MessageService,限定符= {},位置= -1,可選=假,自我=假,不合格= 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());
}
}
爲什麼會發生,以及如何解決它?