In this post I'll show how do tests with Weld and JUnit 4.
So, why we're in trouble to test Weld with Junit. First of all almost everyone framework's that do IoC isn't ease to test with JUnit. This because JUnit makes an environment to do tests.
So, what should I do ?
- Pull dependency weld-se, we'll use it.
- Create a class that extends BlockJUnit4ClassRunner, then override the constructor and override the method createTest()
- Don't forget of file META-INF/beans.xml
If you receive a message like this:
org.jboss.weld.exceptions.DefinitionException: Exception List with 1 exceptions: Exception 0 : java.lang.RuntimeException: javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
then you'll need put a file named jndi.properties
Below an example
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<Object> 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; } }
import javax.inject.Inject; import org.junit.Test; import org.junit.runner.RunWith; import br.com.controle.se.Usuario; @RunWith(WeldJUnit4Runner.class) public class TestingIoC { @Inject private Usuario usuario; @Test public void isNull(){ System.out.println(usuario == null); } }
jndi.properties
java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory java.naming.provider.url=localhost:1099 java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
Now you can enjoy with CDI in your JUnit tests
Comments