javaunit-testingcdiproducercdi-unit

CDI-Unit @Produces not working


First off I googled intensively and according to http://jglue.org/cdi-unit-user-guide/ producing stuff to inject in a unit test should work just fine.

My setup:

@RunWith(CdiRunner.class)
public abstract class CdiUnitBaseTest extends DBUnitBaseTest {
  @Produces
  public EntityManager em() {
    return em; //field from base class filled @BeforeClass
  }
  @Produces
  public Logger logger() {
    return LogManager.getLogger();
  }
}

public class SurveyBeanTest extends CdiUnitBaseTest {

  @Inject
  private SurveyBean bean;

  @Test
  public void surveyWithoutParticipation() {
    Survey s = new Survey();
    s.setParticipation(new ArrayList<Participation>());
    boolean result = this.bean.hasParticipated("12ST", s);

    Assert.assertFalse(result);
  }
}

@Remote(SurveyRemote.class)
@Stateless
public class SurveyBean implements SurveyRemote {

  @Inject
  private Logger log;
  @Inject
  private SurveyDao sDao;
  @Inject
  private ParticipationDao pDao;

  ...
}

The Exception:

org.jboss.weld.exceptions.DeploymentException: Exception List with 3 exceptions:

Exception 0 : org.jboss.weld.exceptions.DeploymentException: WELD-001408: Unsatisfied dependencies for type Logger with qualifiers @Default at injection point [BackedAnnotatedField] @Inject private at.fhhagenberg.unitTesting.beans.SurveyBean.log ...

This means the CdiRunner tries to build my SurveyBean and inject the logger, but it cannot find an object to inject, although I specifically produce it in the base class (same goes for EntityManager).

Anybody knows how to fix this?

PS: tags I was not allowed to add: cdi-unit, jglue


Solution

  • You need to put your producer methods into a separate class from DBUnitBaseTest. This class is abstract and cannot be used as a CDI producer. Both producer methods for em and logger.

    This is because the class having producer methods/fields must be a CDI bean itself - an instance of that class is created by CDI prior to calling producer methods. And CDI cannot create beans from abstract class. Also, @Producer annotations are not inherited, therefore methods inherited by SurveyBeanTest are not treated as producers.