如何使用AsyncFeatureSpec?

时间:2019-04-21 12:08:03

标签: scala bdd scalatest

我正在尝试使用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`")  

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

1 个答案:

答案 0 :(得分:2)

shouldBe匹配器可用于像这样检查接收到的异常的类型

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

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

  

...第二项测试将隐式转换为Future[Assertion]   并注册。隐式转换是从Assertion到   Future[Assertion],因此您必须在某些ScalaTest中结束同步测试   断言或匹配器表达式。如果测试不会以其他方式结束   输入Assertion,则可以在测试结束时放置succeed

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

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