3

因为@BeforeClass回调不适用于 arquillian 测试,所以我尝试在@PostConstruct测试的回调中初始化一些字段。部署中有一个beans.xml,我也尝试添加@Startup注释和无参数构造函数,但没有效果。尽管 CDI 正在工作,并且正在为测试的其他领域执行所有注入,但@PostConstruct没有被调用。我错过了什么吗?

我正在Arquillian 1.0.0.Final使用JBoss 7.1.1.Final. 我不是在寻找解决方法 - 我可以使用@Before回调。但这显然不是最理想的,因为我只需要为所有测试初始化​​一次值。更重要的是,观察到的行为似乎与我对 CDI 的理解相矛盾。

这是我的测试要点:

    @RunWith(Arquillian.class)
    public class UploadResetterTest {

        @Deployment
        public static Archive<?> createTestArchive() {

            return ShrinkWrap
                    .create(WebArchive.class, "uploadResetTest.war")
                    .addPackages(true, "my.package")
                    .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
        }

        Map<String, String> predicates = new HashMap<String, String>();

        @Inject
        Logger log;

        @PostConstruct
        public void postConstruct() {
            log.info("postconstruct");

            // here I am trying to fill the map
            predicates.put("type", UploadTypes.TALLY.toString());
        }

        @Test
        public void testResetTallies() throws Exception {

           // here the map is still empty
            predicates.get("type");
    }
4

1 回答 1

3

@PostConstruct would not be invoked for a test class instance used in an Arquillian test. While Arquillian performs non-contextual CDI injection into the injection points of a test class instance, it is not responsible for constructing the instance itself (JUnit or TestNG does this), and neither is construction of the test class instance managed by the CDI container or any other service container (this explains why @PostConstruct is ignored).

You're best bet therefore is to use @Before. You do raise a good point though, and it might be worth investigating whether the JUnit and TestNG runners provide hooks so that CDI or other DI providers can manage or hook into the test instance lifecycle.

于 2012-11-28T14:00:00.987 回答