Mystagogue
Mystagogue

Reputation: 343

How can I combine shared tests with fixtures that require cleanup?

Currently, I have a set of shared Scalatest tests that live in a trait and are mixed in to test classes where necessary, like so:

trait SharedBehavior{

    def supportsCoolFeature(){
//Testing happens here
    }

    def doesNotSupportCoolFeature(){
//Testing happens here
    }
}
class MyItemTests extends SharedBehavior{

 "A-Type Items" should behave like supportsCoolFeature(itemA)

 "B-Type Items" should behave like doesNotSupportCoolFeature(itemB)
}

Unfortunately, itemA and itemB are Scala class instances that refer to objects that live in the database. To run these tests, I need to create the corresponding database records and then delete them after the test. How can I effectively use fixture strategies that allow me to perform setup and teardown with shared tests?

Though its not ideal, I'd be willing to accept a solution that does setup and teardown once for the whole suite. I can write the tests so that they won't interfere with each other, but I need to keep the DB from getting cluttered over time.

Upvotes: 6

Views: 445

Answers (1)

Mario Galic
Mario Galic

Reputation: 48420

Try

class MyItemTests extends SharedBehavior with BeforeAndAfterEach with DbSupport {

  override def afterEach(): Unit = {
    db.deleteAll()
  }

  def itemA: Item = {
    val item = createItemA
    db.insert(item)
    item
  }

  def itemB: Item = {
    val item = createItemB
    db.insert(item)
    item
  }

 "A-Type Items" should behave like supportsCoolFeature(itemA)

 "B-Type Items" should behave like doesNotSupportCoolFeature(itemB)
}

trait SharedBehavior {

    def supportsCoolFeature(item: => Item) {
      // assert on item
    }

    def doesNotSupportCoolFeature(item: => Item) {
      // assert on item
    }
}

trait DbSupport {
  val db = {
    // initialise dataase
  }
}

Upvotes: 2

Related Questions