org.scalatest: Global setup (like beforeAllSuites?

2020-03-01 10:11发布

问题:

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?

回答1:

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.