Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/380.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用Guice注入字段对Jersey资源进行单元测试_Java_Junit_Jersey_Guice - Fatal编程技术网

Java 使用Guice注入字段对Jersey资源进行单元测试

Java 使用Guice注入字段对Jersey资源进行单元测试,java,junit,jersey,guice,Java,Junit,Jersey,Guice,我有一个Jersey资源,我想用JUnit测试它。资源使用GUI提供程序注入某些字段: @Path("/example/") class ExampleResource { @Inject Provider<ExampleActionHandler> getMyExampleActionHandlerProvider; @GET @Produces(MediaType.APPLICATION_JSON) public List<Exam

我有一个Jersey资源,我想用JUnit测试它。资源使用GUI提供程序注入某些字段:

@Path("/example/")
class ExampleResource {
    @Inject
    Provider<ExampleActionHandler> getMyExampleActionHandlerProvider;

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public List<ExamplePojo> getExampleList() {
        ExampleActionHandler handler = getMyExampleActionHandlerProvider.get();
        handler.doSomething();
    ...
显然,Guice没有机会初始化
ExampleResource
中的字段,因此
handler.doSomething()
调用不会导致NullPointerException


有没有一种方法可以告诉Jersey使用GUI实例化ExampleResource类,以便提供程序工作?

一种方法是将测试分解为几个步骤。您需要创建用于配置服务的喷油器,并测试该喷油器(请参阅和)。使用这些测试,您可以确保有正确的绑定。 拥有注入器后,使用从中获取ApplicationDescriptor对象

ExampleResource exampleResource = injector.getInstance(ExampleResource.class);
Assert.assertEquals(myList, getExampleList());

这种方法的问题在于Jersey所具有的魔力都不可用——比如@DefaultValue()注释字段。事实上,我已经按照我希望的方式完成了这项工作,只是想把它总结成一些可以发布的东西。我知道这有点晚了,但万一你仍然看到这一点,你最终做了什么?@minichate你完成了吗?
ExampleResource exampleResource = injector.getInstance(ExampleResource.class);
Assert.assertEquals(myList, getExampleList());