gpt4 book ai didi

spring - 如何单元测试 spring @Transactional 是否存在?

转载 作者:行者123 更新时间:2023-12-02 04:37:01 31 4
gpt4 key购买 nike

我想知道如何进行单元测试以确保我所有的 DAO 都具有 propagation=MANDATORY。我只实现了一个单元测试来调用 dao.getAll() 而无需事务,如果没有异常则失败。但这不是一种完整的测试,我无法检查所有子方法。

这就是我现在拥有的:

String[] beanNamesForType = applicationContext.getBeanNamesForType(Dao.class);
for (String beanName : beanNamesForType) {
Dao bean = (Dao) applicationContext.getBean(beanName);

try {
bean.getAll();
fail();
} catch (IllegalTransactionStateException ex) {
//This is expected
}
}

是否有可能只检查所有 DAO 方法是否都通过所需的事务传播进行代理?也许使用反射?

最佳答案

我通常使用以下 JUnit 测试用例:

/**
* Test if all the @Services bean are annotated with the @Transactional
* annotation.
*/
@Test
public void testServicesTransactionalAnnotations(){
String[] beansNames = applicationContext.getBeanDefinitionNames();
StringBuilder sb = new StringBuilder();
for(String beanName : beansNames){
Service serviceAnnotation = applicationContext.findAnnotationOnBean(beanName, Service.class);
if(serviceAnnotation != null && applicationContext.findAnnotationOnBean(beanName,
Transactional.class) != null){
Transactional transactional = applicationContext.findAnnotationOnBean(beanName,
Transactional.class);
if(!transactional.propagation().equals(Propagation.MANDATORY)){
sb.append("Missing @Transactional Annotation in bean:").append(beanName).append("\n");
}
}
Assert.assertTrue(sb.toString(), StringUtils.isBlank(sb.toString()));
}

它检查所有用@Service 注释的bean 是否也被标记为Transactional。我使用 String Builder 来了解哪些 bean 缺少注释。

关于spring - 如何单元测试 spring @Transactional 是否存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21757139/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com