I’ve been having a look at Weld recently and wanted to be able to try some stuff out without a container in JUnit, but couldn’t find a JUnit Runner class to do it for me.
I was really suprised how simple it was:
package org.objectopia.test;
import org.jboss.weld.environment.se.Weld;
import org.jboss.weld.environment.se.WeldContainer;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.model.InitializationError;
public class WeldJUnit4Runner extends BlockJUnit4ClassRunner {
private final Class klass;
private final Weld weld;
private final WeldContainer container;
public WeldJUnit4Runner(final Class klass) throws InitializationError {
super(klass);
this.klass = klass;
this.weld = new Weld();
this.container = weld.initialize();
}
@Override
protected Object createTest() throws Exception {
final Object test = container.instance().select(klass).get();
return test;
}
}
Now you can do this :
@RunWith(WeldJUnit4Runner.class)
public class PersistenceTest {
@Inject UserRepository repository;
...
}
Because your test class is just another CDI bean, you can inject any bean reference you require.
This is where the power of CDI comes in to play, you can do something like this:
@Inject @Mock UserRepository userRepository;
And create a producer method to mock it out:
@Produces @Mock UserRepository createUserRepository() { ... }