我有一个泽西资源,我想用JUnit测试。该资源使用Guice Providers注入某些字段:
@Path("/example/")
class ExampleResource {
@Inject
Provider<ExampleActionHandler> getMyExampleActionHandlerProvider;
@GET
@Produces(MediaType.APPLICATION_JSON)
public List<ExamplePojo> getExampleList() {
ExampleActionHandler handler = getMyExampleActionHandlerProvider.get();
handler.doSomething();
...
当使用真实服务器来提供API时,这一切都很有效,但是测试它是有问题的。
我的测试类目前看起来像:
public class ApiTest extends JerseyTest {
public ApiTest() throws Exception {
super();
ApplicationDescriptor appDescriptor = new ApplicationDescriptor();
appDescriptor.setContextPath("/api");
appDescriptor.setRootResourcePackageName("com.my.package.name");
super.setupTestEnvironment(appDescriptor);
}
@Test
public void testHelloWorld() throws Exception {
String responseMsg = webResource.path("example/").get(String.class);
Assert.assertEquals("{}", responseMsg);
}
}
显然,Guice没有机会初始化ExampleResource
中的字段,因此handler.doSomething()
调用不会导致NullPointerException。
有没有办法告诉Jersey使用Guice实例化ExampleResource类,以便提供者工作?
答案 0 :(得分:0)
一种方法是将测试分解为几步。您需要创建正在配置服务的注入器并测试该注入器(请参阅Testing Guice Servlet bindings和Testing Guice can init servlets)。使用这些测试可确保您具有正确的绑定。 获得注入器后,使用
从中获取ApplicationDescriptor对象ExampleResource exampleResource = injector.getInstance(ExampleResource.class);
Assert.assertEquals(myList, getExampleList());