CDI-Unit @Produces not working

送分小仙女□ 提交于 2019-12-24 11:36:11

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/32977594/cdi-unit-produces-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!