如何使用 AsyncFeatureSpec?

How to use 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`")  

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

shouldBe 匹配器可用于检查接收到的异常类型,如下所示

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

这应该可以解决第一个编译器错误。关于第二个错误,我们必须在断言或匹配器表达式中结束async style tests

...the second test will be implicitly converted to Future[Assertion] and registered. The implicit conversion is from Assertion to Future[Assertion], so you must end synchronous tests in some ScalaTest assertion or matcher expression. If a test would not otherwise end in type Assertion, you can place succeed at the end of the test.

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

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