【问题标题】:How to execute several tests with future如何在未来执行多个测试
【发布时间】:2020-06-18 18:17:43
【问题描述】:

我用 Future 和 Await 时间和相同的结构进行了几个 Scala 测试。测试检查一些将文件写入文件系统的方法。

我想执行严格一致的测试,每个测试都必须在之前的测试完成后开始。你能帮我找到路吗?

现在我的测试失败了,因为下一个测试无法检查结果。

class Test1 extends AsyncFunSuite with BeforeAndAfterAll with Eventually with Matchers {
       test("test 1") {
          // clean file system

          Try(
             Await.ready(
             Future(TestedMethod1.run(someArgs)), 10 seconds)
          )

           // checking file
      }

       test("test 2") {
         ..... // the same tests
      }
}

class Test2 extends AsyncFunSuite with BeforeAndAfterAll with Eventually with Matchers {
       test("test 1") {
         ..... // the same tests
      }

       test("test 2") {
         ..... // the same tests
      }
}

【问题讨论】:

    标签: scala concurrency scalatest


    【解决方案1】:

    AsyncFunSuite 默认提供serial execution context

    private final val serialExecutionContext: ExecutionContext = new concurrent.SerialExecutionContext
    implicit def executionContext: ExecutionContext = serialExecutionContext
    

    只有一个单个线程可用,因此如果该线程被Await 阻塞,则无法进行进一步的测试。解决方案是重构您的测试以不使用Await,而是像往常一样简单地映射Future

    Future(TestedMethod1.run(someArgs)).map { result =>
       // assert on result
    }
    

    请注意,您很可能可以使用Eventually avoid

    【讨论】:

    • 感谢您的回复,我用地图重写了测试,但测试执行没有完成。是因为我使用了隐式 val ec = ExecutionContext.fromExecutor(Executors.newFixedThreadPool(20)) 吗?
    猜你喜欢
    • 2022-11-29
    • 2011-06-06
    • 1970-01-01
    • 2019-07-12
    • 2019-09-22
    • 1970-01-01
    • 1970-01-01
    • 2018-10-08
    • 1970-01-01
    相关资源
    最近更新 更多