【发布时间】:2021-04-21 12:51:21
【问题描述】:
以下是用于了解最终如何工作的简化代码。 但它只尝试断言一次,最终不会尝试第二次断言。
package whisk_main
import org.scalatest.concurrent.Eventually.eventually
import org.scalatest.concurrent.Waiters.{interval, timeout}
import org.scalatest.flatspec.AsyncFlatSpecLike
import org.scalatest.matchers.should.Matchers
import org.scalatest.time.{Millis, Seconds, Span}
class EventuallySpec extends AsyncFlatSpecLike with Matchers{
"eventually" should "work, as expected" in {
val runnable = new Runnable {
override def run(): Unit = {
val currentThread = Thread.currentThread()
println(s"$currentThread starts here")
Thread.sleep(5000)
println(s"$currentThread ends here")
}
}
val threadThatSleepsForFiveSeconds = new Thread(runnable)
threadThatSleepsForFiveSeconds.start()
eventually(timeout(Span(15, Seconds)), interval(Span(2, Millis))) {
println("asserting thread state")
threadThatSleepsForFiveSeconds.getState should be(Thread.State.TERMINATED)
}
}
}
下面是异常跟踪:-
Thread[Thread-1,5,main] starts here
asserting thread state
TIMED_WAITING was not equal to TERMINATED
ScalaTestFailureLocation: whisk_main.EventuallySpec at (EventuallySpec.scala:28)
Expected :TERMINATED
Actual :TIMED_WAITING
<Click to see difference>
org.scalatest.exceptions.TestFailedException: TIMED_WAITING was not equal to TERMINATED
at org.scalatest.matchers.MatchersHelper$.indicateFailure(MatchersHelper.scala:344)
at org.scalatest.matchers.should.Matchers$ShouldMethodHelperClass.shouldMatcher(Matchers.scala:6778)
at org.scalatest.matchers.should.Matchers$AnyShouldWrapper.should(Matchers.scala:6822)
at whisk_main.EventuallySpec.$anonfun$new$2(EventuallySpec.scala:28)
我还尝试了以下示例,该示例也记录在 http://doc.scalatest.org/1.8/org/scalatest/concurrent/Eventually.html 上:-
val xs = 1 to 125
val it = xs.iterator
eventually { it.next should be (3) }
上面的例子也失败了下面的例子:-
1 was not equal to 3
ScalaTestFailureLocation: whisk_main.EventuallyExample at (EventuallyExample.scala:12)
Expected :3
Actual :1
<Click to see difference>
org.scalatest.exceptions.TestFailedException: 1 was not equal to 3
at org.scalatest.matchers.MatchersHelper$.indicateFailure(MatchersHelper.scala:344)
at org.scalatest.matchers.should.Matchers$ShouldMethodHelperClass.shouldMatcher(Matchers.scala:6778)
at org.scalatest.matchers.should.Matchers$AnyShouldWrapper.should(Matchers.scala:6822)
at whisk_main.EventuallyExample.$anonfun$new$2(EventuallyExample.scala:12)
请提出建议,为什么在成功之前最终不工作。
【问题讨论】: