【问题标题】:Can you create a distinct Hibernate in-memory database for each thread (for testing)?您可以为每个线程(用于测试)创建一个不同的 Hibernate 内存数据库吗?
【发布时间】:2019-02-03 15:15:09
【问题描述】:

我一直在实现 Hibernate 和 JPA 接口以进行由地图支持的测试。这种数据结构构成了一个非常简单的“数据库”:

// All my database classes implement this (Kotlin) interface.
// "Idd" means "having an ID" as in "ID'd"
interface Idd {
    val id: Long
}

// This simple data structure works as an in-memory database.
//
// The Class is the name of the mapped entity class (which extends Idd)
//
// The inner map uses the ID as the key and the actual objects as
// the value.
//
// ID's are assigned by looking up the Class in the outer map
// and adding one to the size of the inner map (in a synchronized block).
map: SortedMap<Class<Idd>,
               MutableMap<Long, Idd>>

我包装了 Hibernate 的 EntityManager,以便测试可以将新映射传递给它,而不是连接到真实的数据库。我为每个测试传递一个单独的映射,并让测试设置它需要的任何数据,以便在不同线程中同时运行的测试彼此完全分开。

这很好用(这对我的测试来说是一种突破),但是相关的 Hibernate/JPA 类有很多方法,并且在 Hibernate 版本之间变化很大。

我听说 Hibernate 附带了一个内存数据库。这可以与每个线程的单独数据库一起使用以进行测试吗?举个例子就好了!

附:我使用 Sorted/Tree-Map 是因为我可以以可靠的顺序将其打印出来以进行调试。

【问题讨论】:

  • 如果您需要一个内存数据库,那么它不是单元测试。单元测试将使用模拟。如果您需要一个内存数据库,那么它更接近于集成测试。
  • @Michael 我从我的问题中删除了“单位”这个词。是的,与数据库的代码在技术上是集成的。但它非常有用且快速,所以我用我的单元测试来运行这些。
  • @GlenPeterson 呵呵,我刚开始面临同样的问题。你找到解决这个问题的方法了吗?
  • @user007 我在下面发布了一个答案。

标签: java hibernate testing kotlin


【解决方案1】:

使用 H2 内存数据库

我在我的问题中尝试了 map-of-maps 的想法进行测试,但我被诱惑去实现越来越多的 Hibernate 接口,这些接口随着每个新的 Hibernate 版本而改变。此外,它变得非常复杂。最终我把所有这些都去掉了,改用 H2 内存数据库。

您需要将依赖项添加到您的构建中(仅限测试范围):

<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>1.4.200</version>
    <scope>test</scope>
</dependency>

考虑对所有测试使用相同的数据库

我的项目,在我的机器上,大约需要 2 秒来创建 H2 数据库,让 Hibernate 滚动,并在第一次测试之前启动整个事情。如果您能提供帮助,您不想在每个测试中添加等待!最好只初始化一次 H2 数据库并为每个测试使用不同的根节点,这样数据库中就不会有任何交叉。

我数据库中的所有内容都由具有唯一name 字段的公司隔离。用户有一家公司,等等。所以在每次测试开始时,我说,co = newCo("nameUniqueToThisTest"),然后是new User(co, ...) 等。这样来自 2 次测试的数据永远不会被覆盖。如果确实如此,那么您的数据孤岛就不能很好地工作,这是一个更大的问题,值得发现!

这是确保唯一性的 newCo() 方法:

private val coNames: MutableSet<String> = mutableSetOf()

@JvmStatic
fun newCo(nm: String): Company {
    synchronized(coNames) {
        val lcName: String = nm.toLowerCase()
        if (coNames.contains(lcName)) {
            throw IllegalArgumentException("Can't have two companies with the same name (case insensitive): $nm")
        }
        coNames.add(lcName)
    }
    val co = Company(nm)
    save(co) // assigns ID
    return co
}

如果您的数据库没有分离,您可能需要为每个测试创建一个新数据库。如果是这样,您将不需要延迟初始化,因为您将为每个测试使用不同的初始化。在这种情况下,请确保为每个测试更改 myDb 数据库名称,这样它们就不会在每次运行时以不同的顺序覆盖彼此的数据。

我的延迟初始化解决方案

我的解决方案在 Kotlin 中使用延迟初始化的线程安全变量,以确保 Hibernate 和 DB 以及数据库创建仅在第一次测试之前发生一次,并由所有后续测试共享(请参阅上面关于唯一性的说明)。在 Java 中,您可以使用 LazyRef 或其他一些线程安全的一次性初始化来代替 Kotlin 的 by lazy。

private val initialized: Boolean by lazy {
    // TODO: Initialize Logging Here!

    val factory: EntityManagerFactory = try {
        val props = mapOf(
                // Tell Hibernate to use H2, in memory, the myDb database.
                "hibernate.connection.url" to "jdbc:h2:mem:myDb",
                "hibernate.connection.useUnicode" to "true",
                "hibernate.connection.characterEncoding" to "UTF-8",
                "hibernate.hbm2ddl.auto" to "validate",
                // c3p0.max_size is the only option needed to enable c3p0
                "hibernate.c3p0.max_size" to "60",
                "hibernate.c3p0.timeout" to "599",
                "hibernate.bytecode.use_reflection_optimizer" to "false",
                "hibernate.current_session_context_class" to "thread",
                "hibernate.format_sql" to "true",
                "hibernate.max_fetch_depth" to "3",

                // Without the drop, had more schema initialization issues.
                "javax.persistence.schema-generation.database.action" to "drop-and-create",

                // New for MySQL 8?
                "javax.persistence.sharedCache.mode" to "NONE",
                "javax.persistence.validation.mode" to "NONE")

        val tempFactory: EntityManagerFactory = Persistence.createEntityManagerFactory(
                "my.app.persistence",
                props)

        println("H2 EntityManager Initialized")

        // Returns the tempFactory just created.
        // The try-block evaluates in Kotlin.
        tempFactory

    } catch (ex:Throwable) {
        // Make sure you log the exception, as it might be swallowed
        println("ERROR: Initial JPA entityManagerFactory creation failed:\n$ex")
        println("Caused by:\n" + ex.cause)
        throw ex
    }

    entityManagerFactory.set(factory)
    commit()

    // Return true as the value for the `initialized` variable.
    true
}

@JvmStatic
fun testDbInMemory() {
    if (!initialized) {
        throw IllegalStateException("Couldn't initialize Hibernate")
    }
}

然后在每个 Junit (kotlin test) 测试类文件的顶部使用我放置的 DB:

@BeforeTest
fun before() {
    TestGlobals.testDbInMemory()
}

@AfterTest
fun after() { HibernateUtil.commit() }

BeforeTest 是为了确保数据库初始化。 AfterTest 是为了确保任何未提交的事务在与它们相关的测试上(或附近)爆炸。它使调试变得更加容易。

【讨论】:

    猜你喜欢
    • 2021-09-21
    • 2013-04-07
    • 1970-01-01
    • 1970-01-01
    • 2016-08-23
    • 2021-12-14
    • 2014-02-10
    • 2020-04-20
    • 2023-03-15
    相关资源
    最近更新 更多