CDI ve JUnit ile sunucuya (tomcat , jboss vb..) gerekli olmadan birim testleri yapılabilmektedir.
Bunun için junit ve weld se kütüphanesi bağımlılıklarını ekleyelim
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.weld.se</groupId>
<artifactId>weld-se-core</artifactId>
<version>2.2.16.Final</version>
<scope>test</scope>
</dependency>
Test kodu yazabilmek için öncelikle bir WeldContext sınıfı ekleleyim
import org.jboss.weld.environment.se.Weld;
import org.jboss.weld.environment.se.WeldContainer;
public class WeldContext {
public static final WeldContext INSTANCE = new WeldContext();
private final Weld weld;
private final WeldContainer container;
private WeldContext() {
this.weld = new Weld();
this.container = weld.initialize();
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
weld.shutdown();
}
});
}
public <T> T getBean(Class<T> type) {
return container.instance().select(type).get();
}
}
Bu şekilde bean'leri yöneten bir sınıf yaratılmış olur.
Şimdi bir Junit testleri için Runner sınıfı yaratıyoruz:
import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.model.InitializationError;
public class WeldJUnit4Runner extends BlockJUnit4ClassRunner {
public WeldJUnit4Runner(Class<Object> clazz) throws InitializationError {
super(clazz);
}
@Override
protected Object createTest() {
final Class<?> test = getTestClass().getJavaClass();
return WeldContext.INSTANCE.getBean(test);
}
}
Artık test sınıfını aşağıdaki gibi yazabiliriz:
import javax.inject.Inject;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(WeldJUnit4Runner.class)
public class MyUnitTest {
@Inject
com.test.Test testObj;
@Test
public void myTest(){
String message=testObj.getMessage();
Assert.assertEquals("Merhaba CDI Tomcat", message);
}
}
Görüldüğü gibi bizim yarattığımız Test sınıfı inject edilmiştir. Eğer classpath'in META-INF'de beans.xml yok ise aşağıdaki gibi bir hata alabilirsiniz :
Caused by: java.lang.IllegalStateException: WELD-ENV-000016: Missing beans.xml file in META-INF
at org.jboss.weld.environment.se.Weld.initialize(Weld.java:131)
at com.test.WeldContext.
(WeldContext.java:15)
at com.test.WeldContext.(WeldContext.java:8)
... 18 more
Bunu çözmek için beans.xml'i META-IF klasörüne (yok ise yaratılması gerekir) ekleyin :
<?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"
version="1.1" bean-discovery-mode="all">
</beans>
Artık birim testiniz başarıyla çalışması gerekir.
Bu örnek http://memorynotfound.com/java-se-unit-testing-cdi-junit-jboss-weld-se sayfasından yararlanılarak yapılmıştır.