1
votes

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/

1
Your resource file is handled by the container you're deploying to, Tomcat if I had to guess. Resource injection is not handled directly by CDI. - John Ament

1 Answers

0
votes

If you want @Resource to be handled in unit tests perhaps you can look at ejb-cdi-unit it runs the tests in Weld-SE and provides a CDI-Extension which replaces @Resource by @Inject so you can define in your tests an CDI-Alternative to be injected.