1

I am trying to write asynchronous test with AsyncFeatureSpec as the following:

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`")
    }

  }

}

the compiler complains:

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`")  

At the first scenario, I would like to test against the received exception type and I do not know, how to do it.

softshipper
  • 32,463
  • 51
  • 192
  • 400

1 Answers1

2

shouldBe matcher can be used to check against the received exception's type like so

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

which should resolve the first compiler error. Regarding the second error, we must end async style tests in an assertion or matcher expressions:

...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.

Thus writing succeed at the end of a test body will temporarily satisfy the type checker until we write actual checks:

scenario("Send data to a server when Kafka is UP") {
  ...
  succeed // FIXME: add proper checks
}
Mario Galic
  • 47,285
  • 6
  • 56
  • 98