用BeforeAndAfter测试,表放入后,表还在那里

时间:2015-12-19 11:37:27

标签: scala integration-testing scalatest

我正试图在tdd做一个小小的集成测试,以寻找我一直在修补的想法。

我不是TDD的新手,但也不是专家。我昨天刚刚在ScalaTest开始使用它,所以我在这里。

这是有效的:

class BookTest extends FlatSpec with Matchers with ScalaFutures with BeforeAndAfter
{
  implicit val defaultPatience =
    PatienceConfig(timeout = Span(5, Seconds), interval = Span(500, Millis))

  val db = Database.forURL("jdbc:sqlite:/home/teolha/test.sqlite", driver = "org.sqlite.JDBC")

  private val books = Books.all

  val setup = DBIO.seq(
    (books.schema).create,

    // Insert some dummy data
    books += new Book(-1, 0, "Awesome Title #1"),
    books += new Book(-1, 1, "Gorgeous Sequel"),
    books += new Book(-1, 2, "Mehmeh Prequel")
  )

  db.run(setup)

  "Books" should "be a Sequences of Books" in
  {
    val bookList: Future[Seq[Book]] = db.run(books.result)
    whenReady(bookList)
    {
      result => {
        result shouldBe a [Seq[_]] // Remember type erasure
        result(0) shouldBe a [Book]
      }

    }
  }

  "Books" should "contain the books we inserted" in
  {
    val bookList = db.run(books.result)
    whenReady(bookList)
    {
      result =>
      {
        result should have length 3
        (result(0).title shouldEqual "Awesome Title #1") (after being lowerCased)
        (result(1).title shouldEqual "Gorgeous Sequel") (after being lowerCased)
        (result(2).title shouldEqual "Mehmeh Prequel") (after being lowerCased)
      }
    }
  }
}

现在我对此设置存在多个问题:

  1. 我更喜欢内存数据库
  2. 我想在每次测试后删除所有表并设置它们 在下一个之前再次进行并在特定测试中执行插入
  3. 所以我尝试过这样的事情:

    class BookTest extends FlatSpec with Matchers with ScalaFutures with BeforeAndAfter {
      implicit val defaultPatience =
        PatienceConfig(timeout = Span(5, Seconds), interval = Span(500, Millis))
    
      val db = Database.forURL("jdbc:sqlite:/home/teolha/test.sqlite", driver = "org.sqlite.JDBC")
    
      private val books = Books.all
    
      before {
        db.run(setup)
      }
    
      after {
        db.run(tearDown)
      }
    
      val setup = DBIO.seq(
        (books.schema).create
      )
    
      val tearDown = DBIO.seq(
        (books.schema).drop
      )
    
      "Books" should "be a Sequences of Books" in {
        // Insert some dummy data
    
        db.run(
          DBIO.seq(
            books += new Book(-1, 0, "Awesome Title #1"),
            books += new Book(-1, 1, "Gorgeous Sequel"),
            books += new Book(-1, 2, "Mehmeh Prequel")
          )
        )
    
        val bookList: Future[Seq[Book]] = db.run(books.result)
        whenReady(bookList) {
          result => {
            result shouldBe a[Seq[_]] // Remember type erasure
            result(0) shouldBe a[Book]
          }
    
        }
      }
    }
    

    理论上这应该有用,不应该吗?嗯,事实并非如此。在测试之后,仍然有一张桌子,它仍然充满了数据。

    如何正确执行此操作?之后我想把它放在一个内存数据库中(如上所述),但是目前用于调试它更有意义。

0 个答案:

没有答案