spring - Spring Boot 中的事务测试 - 如何获取当前会话?
问题描述
Spring 文档对测试中的误报发出警告,Transactional
并提出以下建议:
// ...
@Autowired
SessionFactory sessionFactory;
@Transactional
@Test // no expected exception!
public void falsePositive() {
updateEntityInHibernateSession();
// False positive: an exception will be thrown once the Hibernate
// Session is finally flushed (i.e., in production code)
}
@Transactional
@Test(expected = ...)
public void updateWithSessionFlush() {
updateEntityInHibernateSession();
// Manual flush is required to avoid false positive in test
sessionFactory.getCurrentSession().flush();
}
// ...
我有以下基类:
@SpringBootTest
@Transactional
@AutoConfigureMockMvc
public abstract class BaseSpringBootTest {
和一个扩展它的类,我想应用这种注入的做法sessionFactory
:
public class EmployeeRepositoryTest extends BaseSpringBootTest {
@Autowired
SessionFactory sessionFactory
但我得到:
NoSuchBeanDefinitionException: No qualifying bean of type 'org.hibernate.SessionFactory' available
我也试过注射
@Autowired
EntityManagerFactory entityManagerFactory;
然后调用:
SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);
sessionFactory.getCurrentSession();
但这会引发以下异常:
org.hibernate.HibernateException: No CurrentSessionContext configured!
如何currentSession
在测试中获得参考,以便我最终可以调用:
sessionFactory.getCurrentSession().flush();
如 Spring Boot 文档中所述?
解决方案
推荐阅读
- grpc - GRPC-gateway 默认 healthCheck 支持
- cucumber - 如何在 Jira Xray 的测试执行中发送测试信息?
- smalltalk - Pharo Monticello 中的“消息不被理解”失败
- grpc - 从 Cloud Build 连接到 GKE 集群上的 gRPC 服务
- javascript - 当它没有改变大小时如何停止改变大小
- php - 使用 HTML 表单连接到数据库并获取用于制作表格的数据
- c# - 无法进入异步任务
- mysql - 如何在 linux debian 10 (Google Pixelbook) 上安装 mysql workbench
- react-native - ScrollView react native 不显示具有绝对位置的子项
- i3 - 编辑shell命令的基本rofi用法