Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 570
Mystagogue Avatar asked Jun 18 '19 23:06

Mystagogue


1 Answers

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
  }
}
like image 156
Mario Galic Avatar answered Oct 18 '22 12:10

Mario Galic