如何清除/忽略ehcache的数据并通过MockRestServiceServer进行测试?



我们正在运行组件测试用例,其中我们使用缓存加载一些数据。。现在的问题是,当我们尝试其他测试用例时,我们希望重置缓存,因为它不会使用其他数据进行测试。我们如何才能做到这一点。我们在Java中使用spring-boot,并使用Ehcache。

您可以将org.springframework.cache.CacheManager bean注入测试中,并使用它在每次测试之前或之后清除缓存。假设有一个名为testCache的缓存,那么清除缓存的测试类将如下所示:

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cache.CacheManager;
@SpringBootTest
public class IntegrationTest {
   @Autowired
   private CacheManager cacheManager;
   @BeforeEach
   public void setup() {
      cacheManager.get("testCache").clear();
   }
   @Test
   public void testSomething() {
   }
}

你可以在github 上找到一个基于spock的参考测试

最新更新