我必须使用JUnit测试一个返回MongoClient的简单Singleton EJB。 我想我可以试试Arquillian。
使用此代码,我获得了Java.lang.AssertionError,因为EJB不是由容器注入的。哪里我错了?
EJB类:
@Stateless
@Singleton
@ConcurrencyManagement(ConcurrencyManagementType.CONTAINER)
public class MongoClientProviderBean {
private Logger logger = Logger.getLogger(MongoClientProviderBean.class);
private MongoClient mongoClient = null;
@Lock(LockType.READ)
public MongoClient getMongoClient() {
return mongoClient;
}
@PostConstruct
public void init() {
try {
String address = "mongo-host";
int port = 27017;
//TODO: inject del indirizzo e porta
mongoClient = new MongoClient(address, port);
logger.info("Inizializzato mongoclient ("+address+", "+port+")");
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
@PreDestroy
public void tearDown() {
mongoClient.close();
logger.info("Mongoclient chiuso");
}
}
测试类:
@RunWith(Arquillian.class)
public class MongoClientProviderBeanTest {
private static final Logger logger = Logger.getLogger(MongoClientProviderBean.class);
@EJB
MongoClientProviderBean mongoClientProviderBean;
@Deployment
public static JavaArchive createDeployment() {
return ShrinkWrap.create(JavaArchive.class, "test.jar")
.addClasses(MongoClientProviderBean.class, MongoClient.class)
.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml");
}
@Test
public void getMongoClient() throws Exception {
assertNotNull(mongoClientProviderBean);
/*
dummy test
*/
mongoClientProviderBean.getMongoClient();
}
}
POM的一部分:
[...]
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.jboss.arquillian</groupId>
<artifactId>arquillian-bom</artifactId>
<version>1.1.13.Final</version>
<scope>import</scope>
<type>pom</type>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.jboss.arquillian.container</groupId>
<artifactId>arquillian-weld-ee-embedded-1.1</artifactId>
<version>1.0.0.CR9</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.weld</groupId>
<artifactId>weld-core</artifactId>
<version>2.3.5.Final</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.arquillian.junit</groupId>
<artifactId>arquillian-junit-container</artifactId>
<scope>test</scope>
</dependency>
[...]
</dependencies>
[...]
我也尝试过使用Wildfly托管容器,但我得到了这个例外:
org.jboss.arquillian.container.spi.client.container.LifecycleException: Could not start container
at org.jboss.as.arquillian.container.managed.ManagedDeployableContainer.startInternal(ManagedDeployableContainer.java:168)
at org.jboss.as.arquillian.container.CommonDeployableContainer.start(CommonDeployableContainer.java:123)
at org.jboss.arquillian.container.impl.ContainerImpl.start(ContainerImpl.java:199)
[...]Caused by: java.lang.IllegalArgumentException: WFLYLNCHR0001: The path 'null' does not exist
at org.wildfly.core.launcher.Environment.validateWildFlyDir(Environment.java:313)
at org.wildfly.core.launcher.AbstractCommandBuilder.validateWildFlyDir(AbstractCommandBuilder.java:652)
JUnit无法启动容器。