0

我在 junit 测试中使用 Weld SE。它似乎没有注入 CDI bean 的内部字段。我正在使用 Maven 神器weld-se-shaded (4.0.2-Final)

import javax.enterprise.context.ApplicationScoped;

@ApplicationScoped
public class XService {

    @Override
    public String toString() {
        return "hi from XService";
    }
}

// ---

import javax.enterprise.context.ApplicationScoped;

@ApplicationScoped
public class YService {

    @Override
    public String toString() {
        return "hi from YService";
    }
}

// ---

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;

@ApplicationScoped
public class ZService {

    @Inject
    public YService yService;

    @Override
    public String toString() {
        return "hi from ZService";
    }
}

// ---

import org.jboss.weld.environment.se.Weld;
import org.jboss.weld.environment.se.WeldContainer;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import static org.assertj.core.api.Assertions.assertThat;

public class WeldTest {

    private WeldContainer container;

    @Before
    public void startContainer() {
        Weld weld = new Weld();
        weld.disableDiscovery();
        weld.addBeanClasses(XService.class, YService.class, ZService.class);
        container = weld.initialize();
    }

    @After
    public void stopContainer() {
        container.shutdown();
    }

    @Test
    public void shouldCreateXServiceInstance() {
        // ok
        XService xService = container.select(XService.class).get();
        assertThat(xService.toString()).isEqualTo("hi from XService");
    }

    @Test
    public void shouldCreateYServiceInstance() {
        // ok
        YService yService = container.select(YService.class).get();
        assertThat(yService.toString()).isEqualTo("hi from YService");
    }

    @Test
    public void shouldInjectYServiceInZService() {
        // fails
        ZService zService = container.select(ZService.class).get();
        assertThat(zService.toString()).isEqualTo("hi from ZService");

        // yService is null, assertion fails
        assertThat(zService.yService).isNotNull();
    }
}

也不例外,该字段为空。我尝试了构造函数注入,而不是字段注入:

@ApplicationScoped
public class ZService {

    public YService yService;

    @Inject
    public ZService(YService yService) {
        this.yService = yService;
    }

    @Override
    public String toString() {
        return "hi from ZService";
    }
}

在这种情况下,我会收到一条异常消息:org.jboss.weld.exceptions.UnsatisfiedResolutionException: WELD-001334: Unsatisfied dependencies for type ZService with qualifiers

4

1 回答 1

0

似乎 Weld 4 只考虑jakarta.*进口。如果我将javax.*导入更改jakarta.*为示例作品。如果我通过javax.*进口降级到 Weld 3,它也可以工作。

于 2021-10-21T14:24:41.597 回答