![](/img/trans.png)
[英]Spring Boot Integration Test for Service method annotated with @Transactional(propagation = Propagation.REQUIRES_NEW)
[英]@Caching method called from spring boot test [annotated with @Transactional] not working
我正在使用Redis緩存和Spring Boot批注[@Cacheable和@CahePut],我做了RedisManager transactionAware,它將使用外部事務[緩存層的被調用者]
@Bean
public RedisCacheManager cacheManager() {
RedisCacheManager rcm =
RedisCacheManager.builder(redisConnectionFactory())
.cacheDefaults(cacheConfiguration())
.transactionAware()
.build();
return rcm;
}
在進行如下測試時,我正在使用嵌入式redis-:
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureTestDatabase
@Transactional
public class RoleServiceImplTest extends TestingProfile {
@Before
public void setup() throws Exception {
//setup server and services
redisServer = new RedisServer(redisPort);
redisServer.start();
}
@Test
public void getUsersForRoleForTemplateRole() {
// call to caching layer methods directly annotated with @Cachable
}
...兩次[帶有和不帶有@Transactional] spring都無例外地調用cache.put(key,result)
,但是僅在沒有@Transactional的情況下才持久保存值。
無法在互聯網上找到太多東西,因此無法獲得任何幫助。
簡而言之,只需在類或測試方法上放置@Commit
或Rollback(false)
批注。
默認情況下,Spring在測試方法之后回滾每個Transaction。
https://docs.spring.io/spring/docs/current/spring-framework-reference/testing.html#testcontext-tx
在TestContext框架中,事務由
TransactionalTestExecutionListener
進行管理,該TransactionalTestExecutionListener
是默認配置的,即使您沒有在測試類上顯式聲明@TestExecutionListeners
也不@TestExecutionListeners
。 但是,要啟用對事務的支持,必須在ApplicationContext
中配置使用@ContextConfiguration
語義加載的PlatformTransactionManager
bean(稍后將提供更多詳細信息)。 另外,您必須在測試的類或方法級別聲明Spring的@Transactional
批注。
聲明式回滾和提交行為
默認情況下,測試事務將在測試完成后自動回滾; 但是,可以在類級別和方法級別通過
@Commit
和@Rollback
批注聲明性地配置事務提交和回滾行為。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.