JPA 2.0 disable session cache for unit tests

二次信任 提交于 2020-12-10 06:45:53

问题


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
}

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?


回答1:


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.

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.




回答2:


There are several way:

  1. Evict Caches Manually

    @Autowired private CacheManager cacheManager;
    
    public void evictAllCaches(){ 
       for(String name : cacheManager.getCacheNames()){
          cacheManager.getCache(name).clear(); 
       } 
    }
    
  2. Turning Off Cache for Integration Test Profile

    • for Spring Boot: spring.cache.type=NONE
    • or
        /** * Disabling cache for integration test */ 
        @Bean public CacheManager cacheManager() {
           return new NoOpCacheManager(); 
        }
  1. Use @DirtiesContext

    @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
    class CacheAffectedTest { ...
    

In this case Spring context re-created after every test and test's time in my measure tripling.

  1. For developing Spring Boot Dev Tools turns caching off automatically during the development phase.

See Spring Cache and Integration Testing and A Quick Guide to @DirtiesContext



来源:https://stackoverflow.com/questions/17814372/jpa-2-0-disable-session-cache-for-unit-tests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!