Version 4

    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



    Below an example


    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 {
            this.klass = klass;
            this.weld = new Weld();
            this.container = weld.initialize();
        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;
    public class TestingIoC {
              private Usuario usuario;
              @Test public void isNull(){
                        System.out.println(usuario == null);






    Now you can enjoy with CDI in your JUnit tests