org.scalatest: Global setup (like beforeAllSuites?)
Asked Answered
A

1

12

I have a scala application with some test using org.scalatest. These test need some global setup (and teardown), in order to manage the test database.

Please don't tell me my tests should not hit the database and I should do it the Java-DAO-Stub-WTF-Overkill-Way™ :-).

I'm running the tests using SBT, which provides a way to execute code before and after test:

    testOptions in Test += Tests.Setup( () => println("Setup") )

    testOptions in Test += Tests.Cleanup( () => println("Cleanup") )

Unfortunately I cannot access the classes in question there. Unsurprisingly, importing them into build.sbt does not work either.

Any ideas?

Amur answered 13/12, 2011 at 9:27 Comment(1)
I had a very similar aim, and found one solution to it. Check this question: #27273311 Wanted to keep also the initialization step as a test class.Goodin
P
4

You can use the BeforeAndAfterAll or BeforeAndAfter traits, depending upon your needs.

BeforeAndAfterAll:

Trait that can be mixed into suites that need methods invoked before and after executing the suite. This trait allows code to be executed before and/or after all the tests and nested suites of a suite are run.

So in this instance, you would define a MasterSuite which contains all other Suites/Tests, which extends this trait.

BeforeAndAfter:

Trait that can be mixed into suites that need code executed before and after running each test. This trait facilitates a style of testing in which mutable fixture objects held in instance variables are replaced or reinitialized before each test or suite.

Phenica answered 14/12, 2011 at 10:59 Comment(3)
Defining a MasterSuite would mean that all of my test needed to be defined in one single file, right? For now, I have separated all the database-dependent test into one suite and use BeforeAndAfterAll there. This also has the advantage that I can skip these slow test easily.Amur
Years later, but still relevant for anyone finding the question: you don't need to define all tests in a single file, ScalaTest has composition functionality where you can use class MasterSuite extends Suites(new OneSpec, new TwoSpec) so the composed suites simply need to be on the classpath (the BeforeAndAfterAll Scaladoc has an example of this, so it's easy to recall). Since 2.0 ScalaTest has the @DoNotDiscover annotation so you can stop SBT (or whatever supporting runner) from running all the composed suites, only the master.Collative
Actually the author covers it well here: #15423837Collative

© 2022 - 2024 — McMap. All rights reserved.