6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

DBアクセス層の単体テスト用にデータソースを用意する

Posted at

サーブレットコンテナで動くアプリを開発している時、DBアクセス層のテストをするのに毎回デプロイするのは面倒だし、テストのスコープが結合テストに近くなってしまう。

そんな時には、以下のようなデータソースを用意してやれば、DBアクセス層の単体テストをし易い。

LocalDataSource.scala
import javax.naming.Context
import javax.naming.InitialContext
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource

trait LocalDataSource {
  val JndiObjectName = "java:comp/env/jdbc/XXX"

  def createDS() = {
    System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory")
    System.setProperty(Context.URL_PKG_PREFIXES, "org.apache.naming")

    // 既にあれば作らない
    val ic = new InitialContext
    try {
      ic.lookup(JndiObjectName)
      println("context already exists.")
    } catch {
      case e: Exception => {
        println("no context")
        create(ic)
      }
    }
  }

  private def create(ic: InitialContext) = {
    ic.createSubcontext("java:")
    ic.createSubcontext("java:comp")
    ic.createSubcontext("java:comp/env")
    ic.createSubcontext("java:comp/env/jdbc")
    val ds = new MysqlDataSource
    ds.setUser("your user name")
    ds.setPassword("your password")
    ds.setServerName("localhost")
    ds.setPort(3306)
    ds.setDatabaseName("your database name")
    ic.bind(JndiObjectName, ds)
  }
}
6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?