CDI:@Resource注入junit焊接?

时间:2017-08-10 20:18:47

标签: java junit cdi weld

使用简单的Mongo DB Producer连接到Mongo数据库

@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;
    }
}

我的src / main / resources / META-INF

中的资源文件
<resources>
    <Resource id="mongoUri" class-name="com.mongodb.MongoClientURI" constructor="uri">
    uri  mongodb://localhost/ironman
    </Resource>
</resources>

简单的Junit @RunWith(WeldJUnit4Runner.class)

public class MongoDBProducerTest {
    @Inject
    DB mongoDb;

    @Test
    public void runSampleTest() {
        assertEquals(mongoDb.collectionExists("jobs"), true);
    }
}

收到以下错误: org.jboss.weld.exceptions.WeldException:WELD-000049:无法调用public void test.dingo.query.db.util.MongoDBProducer.init()在test.dingo.query.db.util上抛出java.net.UnknownHostException .MongoDBProducer @ a1cdc6d

使用Weld

<dependency>
    <groupId>org.jboss.weld.se</groupId>
    <artifactId>weld-se</artifactId>
    <version>2.2.8.Final</version>
</dependency>

WeldContext和WeldJUnit4Runner来自这里 - http://memorynotfound.com/java-se-unit-testing-cdi-junit-jboss-weld-se/

1 个答案:

答案 0 :(得分:0)

如果你想在单元测试中处理@Resource,你可以查看ejb-cdi-unit它在Weld-SE中运行测试并提供一个CDI-Extension,用@Inject替换@Resource,这样你就可以定义了你的测试是CDI替代注射。