users@jersey.java.net

[Jersey] Re: JerseyTest with a resource containing _at_Inject

From: Stefan Bodewig <stefan.bodewig_at_freenet.de>
Date: Thu, 23 Oct 2014 18:09:38 +0200

On 2014-10-23, Matyas Bene wrote:

> After much trial and error while trying to test one of my JAX-RS
> resource using the JerseyTest framework (to be precise, I am extending
> JerseyTestNg.ContainerPerClassTest), I narrowed down my problem to the
> @Inject annotation. That is, whenever my resource contains at least 1
> such field annotated with @Inject, any call to that resource inside
> the test framework fails with HTTP-500, even though that field is
> never used. Running the same resource in Glassfish certainly works as
> expected.

I'm using JUnit and Jersey 2.13 but that shouldn't matter too much.

You must make sure the application you return in your test's configure
method contains a valid HK2 binding for the injectee. You will want to
register an AbstractBinder and bind your collaborators there.


Something like

    @Override
    protected Application configure() {
        return new ResourceConfig(Resource.class)
            .register(new AbstractBinder() {
         .register( new AbstractBinder() {
                 @Override
                 protected void configure() {
                     bind(SOME_INSTANCE).to(YOUR_INJECTEE.class);
                 }
         });
    }

or using class based or factory based bindings or whatever suits you
best. I tend to bind mock objects here.

Stefan