JPA 2.0禁用会话缓存以进行单元测试 [英] JPA 2.0 disable session cache for unit tests

查看:56
本文介绍了JPA 2.0禁用会话缓存以进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am writing unit test for my services 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().什么是最佳最佳实践?

While application running, a new transaction is created every time method A entered. But during the unit test execution - when test testMethod entered. So method A doesn't create new one. For proper testing I need to clear cache before every call to service inside test.I don't want to write Session.clear() before any call to service in each unit test. What is the best best practices here?

推荐答案

EntityManager具有方法

The EntityManager has a method clear() that will drop all persistence context:

清除持久性上下文,导致所有受管实体分离.对尚未刷新到数据库的实体所做的更改将不会保留.

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.

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

If you call a query right after that method it will come directly from the database. Not from a cache.

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

If you want to run this before every test, consider using a JUnit @Rule by subclassing ExternalResource and running the method on every before() or after(). You can reuse that in al you database tests.

这篇关于JPA 2.0禁用会话缓存以进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆