单元在@Startup @Singleton bean中测试@PostConstruct方法

时间:2014-01-08 21:37:37

标签: unit-testing java-ee jboss7.x jboss-arquillian

我首先要说的是,我刚开始使用java-ee和arquillian(一般的单元测试)。

我正在使用wildfly 8.0.0CR1。

我有一个类(我将称之为“初始化Bean”),这是一个简单的@Singleton @Startup bean,它使用@PostConstruct方法进行基本的db初始化。

对应的是单元测试,在@Before方法中,截断所有数据库的表,为初始化阶段准备数据库。

问题是在我的单元测试设置之前调用Initialization Bean @PostContruct方法,以便在Initialization Bean @PostContruct方法之后实际调用应该截断所有数据库表的方法。 / p>

如何正确调试@PostContruct @Singleton bean中的@Startup方法?

我希望我已经足够清楚,否则明天我会发布一些真实的代码。 提前致谢

3 个答案:

答案 0 :(得分:2)

您是否使用@javax.ejb.Singleton注释了init bean?

我遇到了同样的问题,然后我注意到我用@javax.inject.Singleton注释了init bean。修复注释后,将调用@PostConstruct方法。

答案 1 :(得分:0)

您可以使用反射来实例化任何@StartUp类,并在每个测试类之前调用​​@PostConstruct方法。显然,这很容易用Spring完成,但我们在这种环境中没有使用Spring。这是我如何做到的一个例子:

public class BaseTest {
    @BeforeClass
    public static void instantiateStartupClasses() throws InvocationTargetException, IllegalAccessException, InstantiationException {
        Reflections reflections = new Reflections("com.company.project");
        //Find all classes annotated with Startup in a given package.
        Set<Class<?>> classes = reflections.getTypesAnnotatedWith(Startup.class);
        for(Class clazz : classes) {
            if(clazz.isInterface()) continue;
            //Instantiate the object
            Object instantiatedClass = clazz.newInstance();
            //Find any PostConstruct methods on the class and invoke them using the instantiated object.
            for(Method method : clazz.getDeclaredMethods()) {
                if(method.isAnnotationPresent(PostConstruct.class)) {
                    //Invoke the post constructor method.
                    method.invoke(instantiatedClass);
                }
            }
        }
    }
}

答案 2 :(得分:-1)

有一种方法可以解决问题。您不应该使用Autowire使用@PostConstruct方法创建bean对象。您可以通过java代码创建bean。

1在测试类中制作一个这样的方法:

private BeanFactory getTestBeanFactory() {
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath*:<your test context>-test.xml");
    return applicationContext.getAutowireCapableBeanFactory();
}
测试中的

2执行此代码:

// get your bean object
YourBean yourBean = getTestBeanFactory().getBean(YourBean.class);
// call manually a post construct method of your bean
yourBean.<the post construct method of your bean>();
// do something with the yourBean
...

它工作正常

祝你好运

相关问题