【问题标题】:Java Play 2.4 write test case for class using injectionJava Play 2.4 使用注入为类编写测试用例
【发布时间】:2016-02-10 14:58:51
【问题描述】:

最近我在 Java 项目中使用 play 2.4 框架。

我正在使用 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());
        }
    });
}

【问题讨论】:

  • 可以分享一下测试代码吗?
  • 您好,Tomer,感谢您的回复,我已修改问题并添加了测试代码。
  • 你想测试弹性搜索功能吗?意思是你加载一个实际的弹性搜索集群并想要查询它?或者您想“模拟”来自 wsClinet 的重新调整的结果?
  • 我想测试我创建的 ElasticSearch 类功能。我正在使用 WSClient 向 ElasticSearch DB 发送调用

标签: java dependency-injection playframework-2.4


【解决方案1】:

在编写您拥有的选项之前,我建议使用elastic4s。 这个第三方库将帮助您编写更实用的代码,并为您提供非常好的 dsl 来编写查询。 还有一件事,我不知道您使用 elasticsearch 的用例是什么,但我建议您使用其他客户端而不是其他 api,这将为您提供更安全的连接和更高的效率。

你得到了 NPE,因为你自己用 new 安装了 ElasticSearch,并且不要让你的接线感到迷惑,这就是 WSClient 为空的原因。

现在供您选择, 你有两个选择:

将 WithApplication 添加到您的测试中,这将基本上加载您的应用程序,这将使您可以访问 Guice 注入器,您可以从中获取 ElasticSearch 类,您有两种方法可以做到这一点:

  1. 如playdocumentation中所述,使用

         import play.api.inject.guice.GuiceInjectorBuilder
         import play.api.inject.bind
         val injector = new GuiceInjectorBuilder()
         .configure("key" -> "value")
         .bindings(new ComponentModule)
         .overrides(bind[Component].to[MockComponent])
         .injector
    
         val elasticsearch = injector.instanceOf[ElasticSearch]
    
  2. 通过导入 Play

         import play.api.Play 
         val elasticsearch = Play.current.injector.instanceOf(classOf[ElasticSearch])
    
  3. 使用 FakeApplication:只需获取虚假应用程序注入器,并使用它来获取 ElasticSearch 类的实例。

我不喜欢上面的选项,因为您需要运行一个应用程序,这会使您的测试变得非常缓慢。 我建议您自己创建 WSClient 并用它实例化 ElasticSearch 类,然后运行您的测试。

val httpClient = NingWSClient.apply()
val elasticsearch = new ElasticSearch(httpClient)

这是一个更轻便的解决方案,应该可以让您的测试运行得更快。

【讨论】:

    猜你喜欢
    • 2015-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-21
    • 2016-02-26
    • 1970-01-01
    相关资源
    最近更新 更多