How to test Spring's declarative caching support on Spring Data repositories?

前端 未结 2 539
情深已故
情深已故 2020-11-28 06:29

I have developed a Spring Data repository, MemberRepository interface, that extends org.springframework.data.jpa.repository.JpaRepository. Me

2条回答
  •  盖世英雄少女心
    2020-11-28 07:12

    I tried testing the cache behavior in my app using Oliver's example. In my case my cache is set at the service layer and I want to verify that my repo is being called the right number of times. I'm using spock mocks instead of mockito. I spent some time trying to figure out why my tests are failing, until I realized that tests running first are populating the cache and effecting the other tests. After clearing the cache for every test they started behaving as expected.

    Here's what I ended up with:

    @ContextConfiguration
    class FooBarServiceCacheTest extends Specification {
    
      @TestConfiguration
      @EnableCaching
      static class Config {
    
        def mockFactory = new DetachedMockFactory()
        def fooBarRepository = mockFactory.Mock(FooBarRepository)
    
        @Bean
        CacheManager cacheManager() {
          new ConcurrentMapCacheManager(FOOBARS)
        }
    
        @Bean
        FooBarRepository fooBarRepository() {
          fooBarRepository
        }
    
        @Bean
        FooBarService getFooBarService() {
          new FooBarService(fooBarRepository)
        }
      }
    
      @Autowired
      @Subject
      FooBarService fooBarService
    
      @Autowired
      FooBarRepository fooBarRepository
    
      @Autowired
      CacheManager cacheManager
    
      def "setup"(){
        // we want to start each test with an new cache
        cacheManager.getCache(FOOBARS).clear()
      }
    
      def "should return cached foobars "() {
    
        given:
        final foobars = [new FooBar(), new FooBar()]
    
        when:
        fooBarService.getFooBars()
        fooBarService.getFooBars()
        final fooBars = fooBarService.getFooBars()
    
        then:
        1 * fooBarRepository.findAll() >> foobars
      }
    
    def "should return new foobars after clearing cache"() {
    
        given:
        final foobars = [new FooBar(), new FooBar()]
    
        when:
        fooBarService.getFooBars()
        fooBarService.clearCache()
        final fooBars = fooBarService.getFooBars()
    
        then:
        2 * fooBarRepository.findAll() >> foobars
      }
    } 
    

提交回复
热议问题