注册多个相同类型的资源实例

register multiple resource instances of same type

我有一个资源端点,它将 @PathParam 注入构造函数,即每个 @PathParam 值的不同实例。在 Jetty 中一切正常。但是现在我正在尝试使用 Jersey Test Framework 编写单元测试,而且测试框架似乎只支持每种类型一个注册端点。

所以如果我这样做:

@Path("/users")
public class MyResource {

    public MyResource(@PathParam("userId") int userId) {
    }

    @Path("{userId}")
    public String get() {

    }
}

public class MyTest extends JerseyTestNg.ContainerPerClassTest {

    @Override
    protected Application configure() {
        return new ResourceConfig()
                .register(new MyResource(1))
                .register(new MyResource(2));
    }

    @Test
    public void test2() {
        target("/users/1").request().get();
    }

    @Test
    public void test2() {
        target("/users/2").request().get();
    }
}

我看到 test1 和 test2 都在调用 MyResource(1) 的实例。这是预期的吗?是否有调用正确实例的解决方案?

您应该将资源注册为 class。 Jersey 将为您创建它。并处理所有注射。

"The example I posted is dumbed down. In reality, my resource constructor has another injected object that I need to mock. So how would I specify a mocked object parameter for the constructor?"

你可以这样做

@Mock
private Service service;

@Override
public ResourceConfig configure() {
    MockitoAnnotations.initMocks(this);
    return new ResourceConfig()
        .register(MyResource.class)
        .register(new AbstractBinder() {
            @Override
            protected configure() {
                bind(service).to(Service.class);
            }
        });
}

@Test
public void test() {
    when(service.getSomething()).thenReturn("Something");
    // test
}

假设您已经在使用内置的 HK2 DI,并且在您的资源 class 的构造函数上有一个 @Inject 注释,这应该可行。在 AbstractBinder 中,我们使模拟对象可注入。所以现在 Jersey 可以将它注入到你的资源中。

另请参阅:

  • Jersey - How to mock service