简体   繁体   English

如何从ScalaTest获取指示测试套件故障的返回值?

[英]How can I get a return value from ScalaTest indicating test suite failure?

I'm running a ScalaTest ( FlatSpec ) suite programmatically, like so: 我正在以编程方式运行ScalaTest( FlatSpec )套件,如下所示:

new MyAwesomeSpec().execute()

Is there some way I can figure out if all tests passed? 有什么方法我可以弄清楚是否所有测试都通过了? Suite#execute() returns Unit here, so does not help. Suite#execute()在这里返回Unit ,所以没有帮助。 Ideally, I'd like to run the whole suite and then get a return value indicating whether any tests failed; 理想情况下,我想运行整个套件,然后获得一个返回值,指示是否有任何测试失败; an alternative would be to fail/return immediately on any failed test. 另一种方法是在任何失败的测试中立即失败/返回。

I can probably achieve this by writing a new FlatSpec subclass that overrides the Scalatest Suite#execute() method to return a value, but is there a better way to do what I want here? 我可以通过编写一个新的FlatSpec子类来覆盖Scalatest Suite#execute() #cute Suite#execute()方法来返回一个值来实现这一点,但有没有更好的方法来做我想要的呢?

org.scalatest.Suite also has run function, which returns the status of a single executed test. org.scalatest.Suite也有run函数,它返回单个执行测试的状态。

With a few tweaking, we can access the execution results of each test. 通过一些调整,我们可以访问每个测试的执行结果。 To run a test, we need to provide a Reporter instance. 要运行测试,我们需要提供Reporter实例。 An ad-hoc empty reporter will be enough in our simple case: 在我们的简单案例中,一位临时空记者就足够了:

val reporter = new Reporter() {
  override def apply(e: Event) = {}
}

So, let's execute them: 那么,让我们执行它们:

import org.scalatest.events.Event
import org.scalatest.{Args, Reporter}

val testSuite = new MyAwesomeSpec()
val testNames = testSuite.testNames

testNames.foreach(test => {
  val result = testSuite.run(Some(test), Args(reporter))
  val status = if (result.succeeds()) "OK" else "FAILURE!"
  println(s"Test: '$test'\n\tStatus=$status")
})

This will produce output similar to following: 这将产生类似于以下的输出:

Test: 'This test should pass'
    Status=OK
Test: 'Another test should fail'
    Status=FAILURE!

Having access to each test case name and its respective execution result, you should have enough data to achieve your goal. 有权访问每个测试用例名称及其各自的执行结果,您应该有足够的数据来实现您的目标。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM