如何将较长的ScalaTest规格切成碎片 [英] How to cut a long ScalaTest spec to pieces
问题描述
我正在测试REST API,代码如下:
I'm testing a REST API, and the code goes like this:
- 设置内容,使用PUSH调用填充数据库
- 测试API a
- 测试API b ...
- Setting up stuff, populating a database using PUSH calls
- Testing API a
- Testing API b ...
该代码当前位于一个相当大的FlatSpec
中:
The code is currently in one rather huge FlatSpec
:
class RestAPITest extends FlatSpec
with Matchers
with ScalatestRouteTest
with SprayJsonSupport
我想删掉"Testing API a/b/..."部分,以使代码更易于管理.尝试这样做似乎是不行的:it
是什么类型-如何将其继续传递,等等.
I would like to chop the "Testing API a/b/..." parts out, to have the code more manageable. Trying to do that seems like a no-no: what's the type of it
- how to pass that on, etc. etc.
那么,推荐这种方式的推荐方式是什么.
So, what's the recommended way to go about such stuff.
基本设置成功后,a/b/...测试可以并行运行.
The a/b/... tests could be run in parallel, once the basic setup has succeeded.
我目前正在a/b/...测试中使用assume
来使它们在初始化失败时取消.
I'm currently using assume
within the a/b/... tests to make them cancel if the initialization failed.
我应该看看固定装置"还是什么?早些时候尝试过BeforeAndAfterAll
,但是并没有真正让它对我有用.
Should I look at "fixtures" or what for this? Have tried BeforeAndAfterAll
earlier, but didn't really get it working for me.
感谢您的指点/意见.您如何使测试套件简短?
Thanks for the pointers / opinions. How do you keep your test suites short?
推荐答案
添加为新答案,因此区别很明显,因此不需要删除上面的讨论.如果我没有做任何错别字,这应该可以工作(我做了测试,并在我的项目中采用了它.)
Adding as a new answer, so the differences are clear and the discussion above need not be removed. If I didn't do any typos, this should work (I did test it, and adopted in my project).
import org.scalatest._
/*
* Mix this trait into any specs that need 'TestA' to have been run first.
*/
trait TestAFirst {
// Reading a 'TestA' object's field causes it to be instantiated and 'TestA' to be executed (but just once).
//
val testASuccess = TestA.success
}
/*
* 'TestA' gets instantiated via the companion object explicitly (thus @DoNotDiscover)
* and creates a success value field. Otherwise, it's a test just like any other.
*/
@DoNotDiscover
class TestA private extends FlatSpec {
private var success = false // read once, by the companion object
behavior of "Root class"; {
it should "run prior to any of the B,C classes" in {
assert(true) // ... A tests
success = true
}
}
}
object TestA {
val success = {
val o= new TestA
o.execute
o.success // getting a value from the executed test ('.execute()' itself doesn't provide a status)
}
}
class TestB extends FlatSpec with TestAFirst {
behavior of "class B"; {
it should "run after A has been run" in {
assume(testASuccess)
assert(true) // ... B tests
}
}
}
class TestC extends FlatSpec with TestAFirst {
behavior of "class C"; {
it should "run after A has been run" in {
assume(testASuccess)
assert(true) // ... C tests
}
}
}
这篇关于如何将较长的ScalaTest规格切成碎片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!