【问题标题】:Spring Boot: Use Hibernate Session in a unit testSpring Boot:在单元测试中使用 Hibernate Session
【发布时间】:2016-07-23 14:09:17
【问题描述】:

在我的 Spring Boot 应用程序中,我访问我的 Hibernate 会话,如以下答案所示:https://stackoverflow.com/a/33881946/272180

现在我还想在单元测试中访问 Hibernate Session。

如何在 Spring Boot 应用程序的单元测试中设置数据源并访问 Hibernate Session?

当我简单地自动装配它时,我得到org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread.

自动装配和使用 @Service 完美无缺。

我的单元测试类看起来像这样的 atm:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = App.class)
@WebIntegrationTest
public class WebTest {

    @Autowired
    private SessionFactory  sessionFactory;

    @Autowired
    private UserService     userService;

    @Test
    public void testService() {

        final List<User> users = userService.getUsers();

        // do something with users
        // ...

    }
}

App.class是指带有main方法的类,用于运行Spring Boot应用程序。

【问题讨论】:

    标签: java spring-boot junit4


    【解决方案1】:

    事实上,解决方案就像将@Transactional 添加到测试类一样简单。

    之后我可以像往常一样使用SessionFactory

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-11
      • 2019-12-10
      • 2016-05-28
      • 2015-07-09
      • 1970-01-01
      • 2017-02-08
      • 2017-10-21
      相关资源
      最近更新 更多