mercredi 29 août 2018

Can you create a distinct Hibernate in-memory database for each thread (for testing)?

I've been implementing Hibernate and JPA interfaces for testing backed by a map of maps. This data structure makes a really simple "database":

// 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>>

I wrap Hibernate's EntityManager so that a test can pass it a new map instead of connecting to a real database. I pass it a separate map for each test and have the test set up whatever data it needs so that tests running simultaneously in different threads are completely separate from each other.

This works great (it was kind of a breakthrough for my testing), but the relevant Hibernate/JPA classes have a lot of methods and change quite a bit between versions of Hibernate.

I've heard that Hibernate ships with an in-memory database. Can this be used with a separate database per thread for testing? An example would be great!

P.S. I use a Sorted/Tree-Map because I can print it out in a reliable order for debugging.

Aucun commentaire:

Enregistrer un commentaire