gpt4 book ai didi

java - 如何测试 EntityManager.persist() 调用

转载 作者:行者123 更新时间:2023-12-01 13:58:06 24 4
gpt4 key购买 nike

我在 Spring 容器中进行了一个简单的测试:

public class JpaCategoryRepositoryTest extends AbstractJpaJavaTestBase {

@Inject
private CategoryService categoryService;

@Test
public void testStoreCategory(){
final Category category = new CategoryBuilder()
.name("Test category")
.build();
assertEquals("Cateogory ID is not assigned", 0L, category.getId());
categoryService.storeCategory(category);
assertNotEquals("Category ID is persistent", 0L, category.getId());
}
}

assertNotEquals 失败。我以为交易还没有提交。好的,我已经更新了测试,添加了事务管理:

public class JpaCategoryRepositoryTest extends AbstractJpaJavaTestBase {

@Inject
private CategoryService categoryService;

@Inject
TransactionTemplate transactionTemplate;

@Test
public void testStoreCategory(){
final Category category = new CategoryBuilder()
.name("Test category")
.build();
assertEquals("Cateogory ID is not assigned", 0L, category.getId());
transactionTemplate.execute(new TransactionCallback<Void>() {
@Override
public Void doInTransaction(TransactionStatus status) {
categoryService.storeCategory(category);
return null;
}
});
assertNotEquals("Category ID is persistent", 0L, category.getId());
}
}

但这并没有帮助。在集成测试期间测试实体已保存的最佳模式是什么?当我在测试失败后检查表时,实际的实体被保存。

最佳答案

在 JPA 规范中,何时准确设置实体的 ID 取决于 JPA 实现。但是,必须在将实体写入数据库时​​设置它。您可以通过调用entityManager.flush()来强制执行此操作。因此,将一个entityManager添加到您的测试中:

@PersistenceContext
private EntityManager entityManager;

并在存储实体后调用flush():

categoryService.storeCategory(category);
entityManager.flush();

应该修复你的测试。

另请参阅:When does the JPA set a @GeneratedValue @Id

关于java - 如何测试 EntityManager.persist() 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19515080/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com