我正在运行调用 future 的嵌套测试套件,测试处理程序将忽略转换内部的任何异常或断言。
class TestManager extends AsyncFlatSpec {
val reporter: Reporter = new Reporter() {
override def apply(e: Event): Unit = {}
}
val suite = new NestedSuite()
suite.testNames.foreach(test => it should test in {
val result = suite.run(Some(test), Args(reporter))
log.info("{}",result.succeeds())
assert(result.succeeds())
})
}
class NestedSuite extends AsyncFlatSpec {
it should "be false" in {
def exampleFunction: Future[Boolean] = {
Thread.sleep(50)
Future.successful(false)
}
exampleFunction.transformWith {
case Success(v) => assert(v)
case Failure(ex) => assert(false)
}
}
it should "also be false" in {
def exampleFunction: Future[Boolean] = {
Thread.sleep(50)
Future.failed(makeSystemException(result_exception))
}
exampleFunction.transformWith { _ =>
throw makeSystemException(result_exception)
}
}
}
这些测试总是成功的。如何正确报告返回未来的异常或错误断言?
你可以试试这个:
import scala.concurrent.Future
import scala.util.{Failure, Success}
import org.scalatest._
import org.scalatest.flatspec.AsyncFlatSpec
import org.scalatest.matchers.should.Matchers
import scala.concurrent.ExecutionContext
class NestedSuite extends AsyncFlatSpec with Matchers {
implicit val ec: ExecutionContext = scala.concurrent.ExecutionContext.Implicits.global
it should "be false" in {
def exampleFunction: Future[Boolean] = Future {
Thread.sleep(50)
false
}
exampleFunction.map { result =>
assert(!result)
}
}
it should "also be false" in {
def exampleFunction: Future[Boolean] = Future {
Thread.sleep(50)
throw new RuntimeException("System error")
}
exampleFunction.failed.map { ex =>
assert(ex.isInstanceOf[RuntimeException])
}
}
}