测试执行完成后打印的单元测试输出
Output of unit test printed after execution of the test finished
我有以下单元测试:
test("All - gather message") {
def fs: List[Future[Int]] = List(Future{
blocking {Thread.sleep(4000)}
println("Finished sleeping in future 1!")
1
}, Future {
blocking {Thread.sleep(3000)}
println("Finished sleeping in future 2!")
2
}, Future {
blocking {Thread.sleep(2000)}
println("Finished sleeping in future 3!")
3
})
val f: Future[List[Int]] = Future.all(fs)
f onComplete { case x => {
println("x is: " + x.get)
assert(x.get == List(1, 2, 3))
}
}
Await.ready(f, 5 seconds)
}
这是测试套件的一部分。
问题是当我的代码没有产生正确的结果时,测试仍然通过并且错误消息出现在测试套件的下一个单元测试的输出中。
我认为这是因为一旦 f
完成,测试函数 returns,只有在此之后 onComplete
块中的代码才会被执行。
我希望只有在 onComplete
中的代码执行后,测试函数才会 return。
我该怎么做?
您的测试没有失败的原因是您的 onComplete 块 运行 在与实际测试方法不同的线程中。考虑这个测试:
class MyTest extends FlatSpec {
it should "get a List" in {
def fs: List[Future[Int]] = List(Future(1))
println("Test thread " + Thread.currentThread().getName)
val f: Future[List[Int]] = Future.sequence(fs)
f onComplete { case x => {
println("Complete thread " + Thread.currentThread().getName)
assert(x.get == List(5))
}}
Await.ready(f, Duration.Inf)
}
}
当 运行 我们得到这个输出并且测试没有失败时:
Test thread: ScalaTest-run-running-MyTest
Complete thread: ForkJoinPool-1-worker-11
您希望断言与测试位于同一线程中。最后,我认为您正在寻找 onComplete 之外的类似内容:
assert(Await.result(f, 5 seconds) == List(1, 2, 3))
我有以下单元测试:
test("All - gather message") {
def fs: List[Future[Int]] = List(Future{
blocking {Thread.sleep(4000)}
println("Finished sleeping in future 1!")
1
}, Future {
blocking {Thread.sleep(3000)}
println("Finished sleeping in future 2!")
2
}, Future {
blocking {Thread.sleep(2000)}
println("Finished sleeping in future 3!")
3
})
val f: Future[List[Int]] = Future.all(fs)
f onComplete { case x => {
println("x is: " + x.get)
assert(x.get == List(1, 2, 3))
}
}
Await.ready(f, 5 seconds)
}
这是测试套件的一部分。
问题是当我的代码没有产生正确的结果时,测试仍然通过并且错误消息出现在测试套件的下一个单元测试的输出中。
我认为这是因为一旦 f
完成,测试函数 returns,只有在此之后 onComplete
块中的代码才会被执行。
我希望只有在 onComplete
中的代码执行后,测试函数才会 return。
我该怎么做?
您的测试没有失败的原因是您的 onComplete 块 运行 在与实际测试方法不同的线程中。考虑这个测试:
class MyTest extends FlatSpec {
it should "get a List" in {
def fs: List[Future[Int]] = List(Future(1))
println("Test thread " + Thread.currentThread().getName)
val f: Future[List[Int]] = Future.sequence(fs)
f onComplete { case x => {
println("Complete thread " + Thread.currentThread().getName)
assert(x.get == List(5))
}}
Await.ready(f, Duration.Inf)
}
}
当 运行 我们得到这个输出并且测试没有失败时:
Test thread: ScalaTest-run-running-MyTest
Complete thread: ForkJoinPool-1-worker-11
您希望断言与测试位于同一线程中。最后,我认为您正在寻找 onComplete 之外的类似内容:
assert(Await.result(f, 5 seconds) == List(1, 2, 3))