使用 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 是为了确保任何未提交的事务在与它们相关的测试上(或附近)爆炸。它使调试变得更加容易。