在所有Scalatesttesting之前或之后做一些事情

我有一套scalatesttesting,用于testingRESTful API的不同端点。 我真的希望他们分成不同的文件以获得最佳组织。

我的问题是如何在所有的testing开始之前(在我的情况下是一个HTTP服务器,但不pipe它是什么),并在所有的testing完成后closures它。

我知道BeforeAndAfterAll,但是只有在一个testing文件里面/之后才能完成。 我需要这样的东西,但是对于所有的testing,例如:

– 在testing之前启动http服务器
– 运行所有testing套件
– closureshttp服务器

预期的方法是使用嵌套套件。 套件有一个nestedSuites方法,返回一个IndexedSeq [Suite](2.0版本,1.9.1版本,它是一个List [Suite])。 套件还有一个runNestedSuites方法,负责执行任何嵌套的套件。 默认情况下,runNestedSuites调用nestedSuites,并且在每个返回的套件上直接调用run,或者如果传递了Distributor,则将嵌套套件放在分发器中,以便它们可以并行运行。

所以你真正想要做的是将Foo和Bar放入类中,并从EndpointTests的nestedSuites方法中返回它们的实例。 有一门课很容易叫做套房。 这是一个使用的例子:

import org.scalatest._ import matchers.MustMatchers class Foo extends FunSpec with MustMatchers { describe("Message here...") { it("Must do something") { } it("Must be ok") { } } } class Bar extends FunSpec with MustMatchers { describe("Hello you...") { it("One more!") { } } } class EndpointTests extends Suites(new Foo, new Bar) with BeforeAndAfterAll { override def beforeAll(configMap: Map[String, Any]) { println("Before!") // start up your web server or whatever } override def afterAll(configMap: Map[String, Any]) { println("After!") // shut down the web server } } 

但是,一个潜在的问题是,如果您使用discovery来查找套件来运行,则会发现EndpointTest,Foo和Bar的全部三个。 在ScalaTest 2.0中,你可以用@DoNotDiscover注释Foo和Bar,而ScalaTest的Runner不会发现它们。 但是,仍然会。 我们目前正在加强sbt,以便它通过否则可发现的套房,用DoNotDiscover注释,但这将在0.13,这还没有出来。 在此期间,您可以通过向Foo和Bar添加一个未使用的构造函数参数来让sbt忽略它们。

或者,你可以只使用一个对象。

 object TestServer { startServer() } 

当你访问对象时,它将被初始化,启动服务器。 只要在你访问对象的主体中创build一个共同的特征。 然后把这个特性混入到你所有的testing中。 完成。

如果您的服务器以守护进程模式运行(例如,在testing模式下的Play!应用程序),则在所有testing运行后,它将自动closures。

好的,find一个方法。 看来(除非有人能纠正我)Scalatest没有“主”套件的function。 但是…你可以build立一个。

你可以从特质组成一个套件。 所以使用我的端点示例:

 class EndpointTests extends FunSpec with MustMatchers with BeforeAndAfterAll with Foo with Bar { override def beforeAll(configMap: Map[String, Any]) { println("Before!") // start up your web server or whatever } override def afterAll(configMap: Map[String, Any]) { println("After!") // shut down the web server } } 

好的,但是testing呢? 注意与FooBar 。 我正在把依赖testing作为特征。 看这里:

 trait Foo extends FunSpec with MustMatchers { describe("Message here...") { it("Must do something") { } it("Must be ok") { } } } trait Bar extends FunSpec with MustMatchers { describe("Hello you...") { it("One more!") { } } }