gpt4 book ai didi

java - JPA 2.0 为单元测试禁用 session 缓存

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:49:26 24 4
gpt4 key购买 nike

我正在为我的服务编写单元测试 e。 G。 :

@Test
@Rollback(value = true)
public void testMethod()
{
// insert test data

myService.Method(); // read/write from DB

// asserts go here
}

在应用程序运行时,每次方法 A 进入时都会创建一个新事务。但是在单元测试执行期间 - 当测试 testMethod 进入时。所以方法 A 不会创建新方法。 为了进行正确的测试,我需要在测试中每次调用服务之前清除缓存。我不想在每个单元测试中调用任何服务之前编写 Session.clear() 。这里的最佳实践是什么?

最佳答案

EntityManager 有一个方法 clear()这将删除所有持久性上下文:

Clear the persistence context, causing all managed entities to become detached. Changes made to entities that have not been flushed to the database will not be persisted.

如果您在该方法之后立即调用查询,它将直接来自数据库。不是来自缓存。

如果您想在每次测试之前运行它,请考虑使用 JUnit @Rule通过子类化 ExternalResource并在每个 before()after() 上运行该方法。您可以在所有数据库测试中重复使用它。

关于java - JPA 2.0 为单元测试禁用 session 缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17814372/

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