【发布时间】:2022-08-20 07:31:36
【问题描述】:
我们正在运行我们的组件测试用例,其中我们使用缓存加载一些数据。现在问题是当我们尝试其他测试用例时,我们想要重置缓存,因为它不会使用其他数据进行测试。我们怎样才能做到这一点。我们正在使用带有 Java 的 Spring Boot 并使用 Ehcache。
标签: java spring-boot ehcache mockrestserviceserver
我们正在运行我们的组件测试用例,其中我们使用缓存加载一些数据。现在问题是当我们尝试其他测试用例时,我们想要重置缓存,因为它不会使用其他数据进行测试。我们怎样才能做到这一点。我们正在使用带有 Java 的 Spring Boot 并使用 Ehcache。
标签: java spring-boot ehcache mockrestserviceserver
您可以将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 的参考测试
【讨论】: