首页 > 解决方案 > 如何使用 AsyncFeatureSpec?

问题描述

我正在尝试编写异步测试,AsyncFeatureSpec如下所示:

import java.net.ConnectException

import org.scalatest._


final class SapRsSpec extends AsyncFeatureSpec
  with Matchers
  with GivenWhenThen {

  feature("Kafka distribution to a server via websocket") {

    scenario("Send data to SAP server when Kafka is DOWN") {
      Given("Kafka server is NOT active")
      When("consumer client get started")
      val ex = SenderActor.run
      Then("print message `Failed to connect to Kafka`")
      ex.failed map { ex =>
        intercept[ConnectException](ex)
      }
    }

    scenario("Send data to a server when Kafka is UP") {
      Given("Kafka server is active")
      When("consumer client get started")
      Then("print message `Successfully connected to Kafka`")
    }

  }

}

编译器抱怨:

Error:(20, 36) type mismatch;
 found   : java.net.ConnectException
 required: org.scalatest.compatible.Assertion
        intercept[ConnectException](ex)
Error:(27, 11) type mismatch;
 found   : Unit
 required: scala.concurrent.Future[org.scalatest.compatible.Assertion]
      Then("print message `Successfully connected to Kafka`")  

在第一种情况下,我想针对收到的异常类型进行测试,但我不知道该怎么做。

标签: scalabddscalatest

解决方案


shouldBematcher 可用于检查接收到的异常的类型,如下所示

ex.failed map { ex => 
  ex shouldBe a [ConnectException]
}

这应该解决第一个编译器错误。关于第二个错误,我们必须在断言或匹配器表达式中结束异步样式测试:

...第二个测试将被隐式转换Future[Assertion] 并注册。隐式转换是 from Assertionto Future[Assertion]因此您必须在某些 ScalaTest 断言或匹配器表达式中结束同步测试。如果测试不会以其他方式结束 type Assertion,则可以放在succeed测试的末尾。

因此succeed,在测试体的末尾写入将暂时满足类型检查器,直到我们编写实际检查:

scenario("Send data to a server when Kafka is UP") {
  ...
  succeed // FIXME: add proper checks
}

推荐阅读