使用 spring 声明式缓存进行集成测试
Integration testing with spring declarative caching
我正在尝试为 Spring Boot 2 应用程序编写集成测试。
一个测试应该测试通过 REST 更新值。
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureTestEntityManager
@Transactional
public class TenantEndpointIT {
@Autowired
private TestRestTemplate template;
@Autowired
private TestEntityManager entityManager;
@Test
public void nok_updateValueForbidden() {
}
}
现在,我认为最简洁的方法是在@Before 方法中使用 TestEntityManager
创建值,然后在实际测试中测试 REST 端点。
但是 REST 端点调用的服务使用Spring 缓存注释进行注释。所以如果我这样做,测试就会失败。我可以直接使用该服务或进行第二次 REST 调用。这会导致使用相同值的其他测试出现问题,因为即使回滚数据库,缓存似乎仍包含该值。 (现在我正在使用@DirtiesContext)。
我的问题是,您如何正确地将测试服务与@Cachable 集成?
有没有办法获取缓存并显式 put/remove?
我尝试自动装配 CacheManager,但它找不到并且失败了。
如果您在测试中添加 @AutoConfigureCache
,它会通过 CacheManager
那个 noops 覆盖您在应用中定义的任何缓存策略。如果您想确保缓存不会干扰您的测试,这将非常有用。
我正在尝试为 Spring Boot 2 应用程序编写集成测试。
一个测试应该测试通过 REST 更新值。
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureTestEntityManager
@Transactional
public class TenantEndpointIT {
@Autowired
private TestRestTemplate template;
@Autowired
private TestEntityManager entityManager;
@Test
public void nok_updateValueForbidden() {
}
}
现在,我认为最简洁的方法是在@Before 方法中使用 TestEntityManager
创建值,然后在实际测试中测试 REST 端点。
但是 REST 端点调用的服务使用Spring 缓存注释进行注释。所以如果我这样做,测试就会失败。我可以直接使用该服务或进行第二次 REST 调用。这会导致使用相同值的其他测试出现问题,因为即使回滚数据库,缓存似乎仍包含该值。 (现在我正在使用@DirtiesContext)。
我的问题是,您如何正确地将测试服务与@Cachable 集成? 有没有办法获取缓存并显式 put/remove? 我尝试自动装配 CacheManager,但它找不到并且失败了。
如果您在测试中添加 @AutoConfigureCache
,它会通过 CacheManager
那个 noops 覆盖您在应用中定义的任何缓存策略。如果您想确保缓存不会干扰您的测试,这将非常有用。