2016-09-02 3 views
0

Slick과 함께 scalatest를 사용할 때 각 테스트 후에 데이터베이스 정리 문제가 발생합니다. 다음과 같이 정의된다테스트 종료 후 H2 데이터베이스 닫기 또는 종료

class H2DatabaseService { 

    val db = Database.forConfig("h2mem1") 

    val questions = TableQuery[Question] 

    def createSchema = 
    db.run(questions.schema.create) 

    def getQuestionById(id: Long): Future[Option[QuestionEntity]] = 
    db.run(questions.filter(_.id === id).result.headOption) 

    def getQuestions: Future[Seq[QuestionEntity]] = 
    db.run(questions.result) 

    def insertQuestion(question: QuestionEntity): Future[Int] = 
    db.run(questions += question) 
} 

class Question(tag: Tag) extends Table[QuestionEntity](tag, "QUESTION") { 
    def id = column[Option[Long]]("QUESTION_ID", O.PrimaryKey, O.AutoInc) 
    def title = column[String]("TITLE") 

    def * = (id, title) <> ((QuestionEntity.apply _).tupled, QuestionEntity.unapply) 
} 

case class QuestionEntity(id: Option[Long] = None, title: String) { 
    require(!title.isEmpty, "title.empty") 
} 

그리고 데이터베이스 :

class H2DatabaseSpec extends WordSpec with Matchers with ScalaFutures with BeforeAndAfter { 
    implicit override val patienceConfig = PatienceConfig(timeout = Span(5, Seconds)) 

    val h2DB: H2DatabaseService = new H2DatabaseService 
    var db: Database = _ 

    before { 
    db = Database.forConfig("h2mem1") 
    h2DB.createSchema.futureValue 
    } 

    after { 
    db.shutdown.futureValue 
    } 

    "H2 database" should { 
    "query a question" in { 
     val newQuestion: QuestionEntity = QuestionEntity(Some(1L), "First question") 
     h2DB.insertQuestion(newQuestion).futureValue 

     val question = h2DB.getQuestionById(1L) 

     question.futureValue.get shouldBe newQuestion 
    } 
    } 

    it should { 
    "query all questions" in { 
     val newQuestion: QuestionEntity = QuestionEntity(Some(2L), "Second question") 
     h2DB.insertQuestion(newQuestion).futureValue 

     val questions = h2DB.getQuestions 

     questions.futureValue.size shouldBe 1 
    } 
    } 
} 

데이터베이스 서비스가 정의한 데이터베이스에 run 메소드를 호출한다 : 여기

테스트의 코드

h2mem1 = { 
    url = "jdbc:h2:mem:test1" 
    driver = org.h2.Driver 
    connectionPool = disabled 
    keepAliveConnection = true 
} 

저는 Scala 2.11.8, Slick 3.1.1, H2 데이터베이스 1.4.192를 사용하고 있습니다. t 2.2.6.

테스트를 실행할 때 나타나는 오류는 Table "QUESTION" already exists입니다. 그래서 shutdown() 메서드는 아무런 효과가 없습니다 (그러나 호출 된 - 디버거에서 확인) 것 같습니다.

아무도 이러한 시나리오를 처리하는 방법을 알고 있습니까? 각 테스트 후에 데이터베이스를 올바르게 정리하는 방법?

답변

0

다른 개체에서 메서드를 호출하여 데이터베이스가 올바르게 정리되지 않았습니다.

H2DatabaseService은 자신의 db 개체이며 테스트 자체입니다. H2 데이터베이스 서비스를 리팩토링 한 후 문제가 수정되어 다음을 호출 함 :

after { 
    h2DB.db.shutdown.futureValue 
}