Mic*_*ner 5 testing junit hibernate hibernate-envers
我想写关于修订的测试。在控制台中,我看到 Hibernate 的更新调用,但没有插入 AUD-Table。
测试方法:
@DataJpaTest
class JPAHistoryTest {
@Test
public void test() {
def entity = // create Entity
def entity2 = // create same Entity
entity2.setPrice(entity2.getPrice() + 10)
entity2.setLastUpdate(entity2.lastUpdate.plusSeconds(10))
service.save(entity)
service.save(entity2)
repository.flush() // Hibernate updates changes
assert repository.findRevisions(entity.id).content.empty == false // FAIL!
}
}
Run Code Online (Sandbox Code Playgroud)
我的实体看起来像:
@Entity
@Audited
class Entity {
@Id @GeneratedValue Long id
@Column(nullable = false) BigDecimal price
}
Run Code Online (Sandbox Code Playgroud)
非常感谢。
正如我发现我保留@DataJpaTest
并添加@Transactional(propagation = NOT_SUPPORTED)
以确保测试方法不会启动事务。因为如果它们将在事务中运行,那么当测试关闭事务时,将写入 envers 历史条目。
@RunWith(SpringRunner)
@DataJpaTest
@Transactional(propagation = NOT_SUPPORTED)
class JPAHistoryTest {
@After
void after() {
repository.deleteAll()
}
@Test
public void testTwoInsert() {
def entity1 = // ...
def entity2 = // ...
sut.save(entity1 )
sut.save(entity2 )
assert repository.findRevisions(entity1.id).content.size() == 1
assert repository.findRevisions(entity2.id).content.size() == 1
}
}
Run Code Online (Sandbox Code Playgroud)
我发现了与您相同的问题并尝试了@michael-hegner 答案,但我使用了类,因此当没有事务(设置为)时TestEntityManager
我无法得到。EntityManager
propagation
NOT_SUPPORTED
就我而言,解决方案是手动提交事务TestEntityManager
,首先保存实体和更改,然后查询修订。
这是一个测试类:
@DataJpaTest
class UserRepositoryTest {
@Autowired
private TestEntityManager testEntityManager;
@Test
public void shouldBeAudited() {
User user = getTestUser();
testEntityManager.persistAndFlush(user);
user.setPassword("tset");
testEntityManager.merge(user);
// This line is critical here to commit transaction and trigger audit logs
testEntityManager.getEntityManager().getTransaction().commit();
// With propagation = NOT_SUPPORTED this doesn't work: testEntityManager.getEntityManager()
AuditReader auditReader = AuditReaderFactory.get(testEntityManager.getEntityManager());
List revisions = auditReader.createQuery()
.forRevisionsOfEntity(User.class, true)
.add(AuditEntity.id().eq(user.getId()))
.getResultList();
assertEquals(1, revisions.size());
}
private User getTestUser() {
User user = new User();
user.setUsername("test");
user.setEmail("test");
user.setPassword("test");
return user;
}
}
Run Code Online (Sandbox Code Playgroud)
在测试后可能必须手动删除用户,因为事务已提交,并且在其他测试中可能会导致一些问题。