如何使用org.scalatest.FunSuite定义测试超时?
在ScalaTest FunSuite中设置测试超时
没问题!在ScalaTest的FunSuite里,有几种简单的方式给测试设置超时,和你熟悉的JUnit超时机制类似,我给你整理两种常用的实现方法:
1. 使用JUnit风格的@Test注解参数
如果你习惯JUnit的写法,ScalaTest兼容JUnit的@Test注解,直接在注解里指定timeout参数即可,单位是毫秒:
import org.scalatest.FunSuite import org.scalatest.junit.JUnitRunner import org.junit.runner.RunWith import org.junit.Test @RunWith(classOf[JUnitRunner]) class TimeoutExampleSuite extends FunSuite { @Test(timeout = 1000) // 设置1秒超时,超过就标记失败 def testWithTimeout(): Unit = { // 模拟耗时操作,这里会触发超时失败 Thread.sleep(1500) } }
2. 使用ScalaTest原生的failAfter方法
如果不想依赖JUnit注解,ScalaTest本身提供了更灵活的failAfter方法,需要先混入Timeouts特质,还能借助SpanSugar用更直观的时间单位(比如1 second、500 millis):
import org.scalatest.FunSuite import org.scalatest.concurrent.Timeouts import org.scalatest.time.SpanSugar._ class TimeoutFunSuite extends FunSuite with Timeouts { test("test with native ScalaTest timeout") { failAfter(1 second) { // 测试代码块,超过1秒就抛出超时异常 Thread.sleep(1200) } } }
这种方式的优势是可以针对测试里的特定代码段设置超时,而不是整个测试方法,时间语法也更易读。另外要注意,超时机制基于线程实现,不管是阻塞操作还是无限循环,只要超过设定时间都会触发失败。
内容的提问来源于stack exchange,提问作者David Portabella
相关产品推荐
相关产品推荐

