Have a simple Mongo DB Producer to connect to Mongo Database
@SuppressWarnings({ "deprecation", "resource" })
@ApplicationScoped
public class MongoDBProducer {
@Resource(name = "mongoUri")
private MongoClientURI mongoClientURI;
private DB database;
@PostConstruct
public void init() throws UnknownHostException {
MongoClient mongoClient = new MongoClient(mongoClientURI);
database = mongoClient.getDB(mongoClientURI.getDatabase());
}
@Produces
public DB createDB() {
return database;
}
}
A resource file in my src/main/resources/META-INF
<resources>
<Resource id="mongoUri" class-name="com.mongodb.MongoClientURI" constructor="uri">
uri mongodb://localhost/ironman
</Resource>
</resources>
And a simple Junit @RunWith(WeldJUnit4Runner.class)
public class MongoDBProducerTest {
@Inject
DB mongoDb;
@Test
public void runSampleTest() {
assertEquals(mongoDb.collectionExists("jobs"), true);
}
}
getting the following error : org.jboss.weld.exceptions.WeldException: WELD-000049: Unable to invoke public void test.dingo.query.db.util.MongoDBProducer.init() throws java.net.UnknownHostException on test.dingo.query.db.util.MongoDBProducer@a1cdc6d
Using Weld
<dependency>
<groupId>org.jboss.weld.se</groupId>
<artifactId>weld-se</artifactId>
<version>2.2.8.Final</version>
</dependency>
WeldContext and WeldJUnit4Runner are from here - http://memorynotfound.com/java-se-unit-testing-cdi-junit-jboss-weld-se/
如果您希望在单元测试中处理@Resource,也许您可以看一下ejb-cdi-unit,它在Weld-SE中运行测试并提供CDI-Extension,它将@Resource替换为@Inject,以便您可以在测试中定义CDI替代注入。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.