Pphoenix
Pphoenix

Reputation: 1473

Annotate variable to be injected by producer

From what I have understood, it should be possible to use a producer to inject any kind of variable in Java with CDI. To test this I created a small unit test.

@RunWith(CdiRunner.class)
public class Test {

    @Inject
    @AnIntProducer
    int i; // Variable to be injected

    @org.junit.Test
    public void test() throws Exception {
        System.out.println(i);
    }
}

I then proceed to create the annotation and producer:

@Qualifier
@Retention(RUNTIME)
@Target({FIELD, TYPE, METHOD})
public @interface AnIntProducer {
}

public class TestProducer {

    @Produces
    @AnIntProducer
    public int i() {
        return 503;
    }
}

When I run the test I assume that it should print 503, but instead I get:

org.jboss.weld.exceptions.DeploymentException:
WELD-001408: Unsatisfied dependencies for type int with qualifiers @AnIntProducer
  at injection point [UnbackedAnnotatedField] @Inject Test.i
  at Test.i(Test.java:0)  

Somehow it seems that the CdiRunner can't find the producer, and I really dont know why. Is there a problem with my setup or have I just misunderstood how injection works?

Upvotes: 2

Views: 789

Answers (1)

jvalli
jvalli

Reputation: 721

CdiRunner examines the imports of your test class and builds a mini-deployment based on referenced classes. When you run the test the producer you've defined isn't included in that mini-deployment.

To include additional classes and packages in your test deployment you'll need to add @AdditionalClasses or @AdditionalPackages to your test class.

Example:

@RunWith(CdiRunner.class)
@AdditionalClasses(TestProducer.class)
public class Test {

You can also use annotations to declare what should be included in the test deployment's beans.xml, so you can activate alternatives, interceptors and decorators that way.

Upvotes: 2

Related Questions