Java Play 2.4使用注入为类编写测试用例
最近我正在使用play 2.4 framework for Java项目
因为我使用的是WsClient库。那个图书馆被注入我的课堂
@Inject WSClient wsClient
现在我正试图为该类编写一个测试用例,但由于wsClient变量的空指针错误,测试用例失败
wsClient.url("some url").get()
你能帮我解决这个问题吗
下面是测试代码
// Class
public class ElasticSearch {
@Inject WSClient wsClient;
public Promise<WSResponse> createIndex() {
Logger.info("Entering ElasticSearch.createIndex()");
Logger.debug("WSClient: " + wsClient);
Promise<WSResponse> response =wsClient.url(this.getEsClient()+ "/" +this.getEsIndexName()).setContentType("application/json").put("");
Logger.info("Exiting ElasticSearch.createIndex()");
return response;
}
}
// Test function
@Test
public void testCreateIndex() {
running(fakeApplication(), new Runnable() {
public void run() {
ElasticSearch esearch= new ElasticSearch();
esearch.setEsIndexName("car_model");
assertNotNull(esearch.createIndex());
}
});
}
# 1 楼答案
在写你的选项之前,我建议使用elastic4s。 这个第三方库将帮助您编写更实用的代码,并为您提供非常好的dsl来编写查询。 还有一件事,我不知道您使用elasticsearch的用例是什么,但我建议使用与rest api不同的客户端,这将为您提供更安全的连接和更高效的服务
你得到了NPE,因为你自己用new安装了ElasticSearch,不让guice为你连接,这就是为什么WSClient为空
现在让你选择, 你有两个选择:
将WithApplication添加到您的测试中,这将基本上加载您的应用程序,这将使您能够访问Guice injector,您可以从中学习ElasticSearch类。您有几种方法可以做到这一点:
如游戏documentation中所述,使用
通过导入Play
使用FakeApplication:只需掌握fake application injector,并使用它来获取ElasticSearch类的实例
我不喜欢上面的选项,因为你需要一个运行的应用程序,这会让你的测试非常慢。 我建议您自己创建WSClient,并用它实例化ElasticSearch类,然后运行测试
这是一个更轻的解决方案,应该可以让你的测试运行得更快