How To Create Junit 4 Tests With Weld

Challenge

You want to write a couple of Integration tests with JUnit and want to use Weld for the CDI part, but don’t know how…


Solution

Add Weld dependency to your maven project

Weld dependency

1
2
3
4
5
6
<dependency>
<groupId>org.jboss.weld.se</groupId>
<artifactId>weld-se</artifactId>
<version>2.3.3.Final</version>
<scope>test</scope>
</dependency>

Create a couple of helper classes:

WeldContext

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
packkage nl.ivonet.helper;
import org.jboss.weld.environment.se.Weld;
import org.jboss.weld.environment.se.WeldContainer;
public class WeldContext {
private final WeldContainer weldContainer;
private WeldContext() {
final Weld weld = new Weld();
this.weldContainer = weld.initialize();
}
public static WeldContext getInstance() {
return WeldContext.Instance.SINGLETON;
}
private static final class Instance {
static final WeldContext SINGLETON = new WeldContext();
}
public <T> T getBean(final Class<T> type) {
return this.weldContainer.instance()
.select(type)
.get();
}
}

WeldJUnit4Runner

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package nl.ivonet.helper;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.model.InitializationError;
public class WeldJUnit4Runner extends BlockJUnit4ClassRunner {
public WeldJUnit4Runner(final Class<Object> clazz) throws InitializationError {
super(clazz);
}
@Override
protected Object createTest() {
return WeldContext.getInstance().getBean(getTestClass().getJavaClass());
}
}

Initialize bean context for test by creating in the src/test/resources/META-INF folder the beans.xml file

beans.xml

1
2
3
4
5
6
7
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
bean-discovery-mode="all">
</beans>

Now write your test:

JUnit test

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import nl.ivonet.helper.WeldJUnit4Runner;
import org.junit.Test;
import org.junit.runner.RunWith;
import javax.inject.Inject;
import static org.junit.Assert.assertNotNull;
@RunWith(WeldJUnit4Runner.class) //The one you created
public class FooTest {
@Inject
private Foo foo; //just an example class to inject
@Test
public void testNotNull() throws Exception {
//meaningless test but enough to illustrate the workings...
assertNotNull(foo);
}
}
  • Run your tests and you should see it working…