CDI injection and JUnit



我正在尝试将JUnit测试添加到使用CDI和JPA的Tomee Web应用程序中。撇开过去两周的不同障碍(包括对堆栈溢出以及其他来源的非常深入的研究),我的问题似乎非常具体:

运行单元测试会给出以下错误消息:

org.apache.openejb.Injector$NoInjectionMetaDataException: 
org.demo.service.GenericServiceTest : Annotate the class with @javax.annotation.ManagedBean so it can be discovered in the application scanning process
at org.apache.openejb.Injector.inject(Injector.java:54)
at org.apache.openejb.OpenEjbContainer$GlobalContext.bind(OpenEjbContainer.java:656)
...

我不明白这一点,因为我已经按照要求对类进行了注释。知道我能做些什么来解决这个问题吗?

(或者错误是否涉及注入的类 - 泛型服务?我无法注释此@ManagedBean,因为它已经@Stateless了)。

以下是我的项目的一些细节:

gradle 依赖项:

dependencies {
compile 'org.apache.commons:commons-lang3:3.3.2'
compile "com.googlecode.json-simple:json-simple:1.1.1"
compile group: 'com.fasterxml.jackson.core', name: 'jackson-annotations', version: '2.8.6'
compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.8.6'
compile 'log4j:log4j:1.2.16'
testCompile "org.apache.openejb:tomee-embedded:1.7.3"
compile "javax:javaee-api:7.0"
compile 'mysql:mysql-connector-java:5.1.16'
}

(我把testCompile放在中间,因为有一张票证说明了顺序的重要性:使用TomEE嵌入式EJBContainer api进行EJB测试:java.lang.ClassFormatError exception)

我的测试类是这样的:

package org.demo.service;
import java.io.File;
import java.util.Properties;
import javax.annotation.ManagedBean;
import javax.ejb.embeddable.EJBContainer;
import javax.inject.Inject;
import javax.naming.NamingException;
import org.apache.openejb.OpenEjbContainer;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
@ManagedBean
public class GenericServiceTest {
private static EJBContainer ejbContainer;
@Inject
private GenericService service;
@Test
public void test() throws NamingException {
System.out.println("service: " + service);
}
@BeforeClass
public static void start() {
Properties p = new Properties();
try {
p.put(EJBContainer.MODULES, new File("bin"));
} catch (Exception e1) {
e1.printStackTrace();
}
p.put(OpenEjbContainer.Provider.OPENEJB_ADDITIONNAL_CALLERS_KEY, GenericService.class.getName());
ejbContainer = javax.ejb.embeddable.EJBContainer.createEJBContainer(p);
}
@Before
public void inject() throws NamingException {
ejbContainer.getContext().bind("inject", this);
}
@AfterClass
public static void shutdownContainer() {
if (ejbContainer != null) {
ejbContainer.close();
}
}
}

也许我在这里完全朝着错误的方向运行 - 请让我知道我是否应该选择不同的方法 - 我想要的只是将单元测试添加到我的 Web 应用程序中(最好不要引入 Weld/JBoss 或其他实现作为我已经在应用程序本身中使用的实现的替代方案)。

提前非常感谢!

我会建议你阅读 http://tomee.apache.org/developer/testing/index.html,有一些例子

关于你的测试,它使用openejb嵌入式而不是tomee嵌入,并将bin/部署为应用程序。 hack bind("inject")仅适用于类路径部署(无模块)。

最新更新