Reputation: 1217
I start by saying that I'm at the very beginning with my adventure with java-ee and arquillian (unit testing in general).
I'm using wildfly 8.0.0CR1.
I've a class (I'm going to call this "Initialization Bean") that is a simple @Singleton @Startup
bean with a @PostConstruct
method that does some basic db's initialization .
It's counterpart is a unit test that inside the @Before
method, truncates all db's tables to prepare the database for the initialization phase.
The problem is that the Initialization Bean @PostContruct
method gets called before my unit test is set up so that the method that should truncate all database table is actually called after the Initialization Bean @PostContruct
method.
How can I debug a @PostContruct
method in a @Singleton
@Startup
bean correctly?
I hope I've been enough clear, otherwise tomorrow I'll post some real code. Thanks in advance
Upvotes: 0
Views: 2259
Reputation: 137
You could use reflection to instantiate any @StartUp classes and invoke the @PostConstruct methods before each test class. Apparently this is easily done with Spring but we are not using Spring in this environment. Here is an example of how I did it:
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);
}
}
}
}
}
Upvotes: 0
Reputation: 21
Did you annotate your init bean with @javax.ejb.Singleton
?
I was experiencing the same problem, then I noticed that I annotated the init bean with @javax.inject.Singleton
. After fixing the annotation the @PostConstruct
method is called.
Upvotes: 2