Persistence testing is done so basic, writing your first unit test will make you cry.
Lets write a test, that says we have corrected Hibernate handling of UUID Primary Keys
Each piece of this test is highlighted in red
I want a test that
doesn't need to test transaction management, and will obtain the database connections from an existing wildfly standalone file, using EntityAssist to simply query execution
@Test
public void testUUIDHibernatePrimaryKeyFromWildfly()
{
WildflyConnectionInfoBuilder.setStandaloneFileName("standalone-full-ha.xml");
BTMAutomatedTransactionHandler.setActive(true);
TestEntity api = new TestEntity()
.setOID(UUID.randomUUID())
.persist();
Optional stored = new TestEntity().builder().find(api.getOid()).get();
assertEquals(stored.get().getOid(),api.getOid());
}
You can swap out
DatabaseModule's using Guiced EE's module loading mechanism,
or even just change the referenced persistence unit name in the module to point to a different location if you want more than one persistence units available for unit testing
Setmodules = GuiceContext.instance().loadIGuiceModules(); modules.removeIf(a -> a.getClass().equals(MyDataBaseModule.class)); modules.add(new MyDatabaseModuleTests());
Dynamically setting your module persistence unit name can be done as shown below
public MyDatabaseModule()
{
if (StaticConfiguration.getRunningEnvironment()
.equals(RunningEnvironment.UnitTest))
{
setPersistenceUnitName(getPersistenceUnitName() + "_UT");
}
}
@Override
public String getPersistenceUnitName()
{
return PersistenceUnitName;
}
Creating keys for your DatabaseModules can be very handy, especially for getting a hold of instances directly without using injection
public static final KeyMODEL_DATASOURCE_KEY = Key.get(DataSource.class, MyDatabaseAnnotation.class); public static final Key MODEL_ENTITYMANAGER_KEY = Key.get(EntityManager.class, MyDatabaseAnnotation.class);
I am then able to get a hold of these instances directly in my test class :
EntityManager em = GuiceContext.get(MyDatabaseBModule.MODEL_ENTITYMANAGER_KEY); assertTrue(em.isOpen());