Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Spring引导:在单元测试中使用Hibernate会话_Java_Spring Boot_Junit4 - Fatal编程技术网

Java Spring引导:在单元测试中使用Hibernate会话

Java Spring引导:在单元测试中使用Hibernate会话,java,spring-boot,junit4,Java,Spring Boot,Junit4,在我的Spring Boot应用程序中,我访问我的Hibernate会话,如下所示: 现在我还想在单元测试中访问Hibernate会话 如何在Spring Boot应用程序的单元测试中设置数据源并访问Hibernate会话 当我简单地自动连线它时,我得到org.hibernate.hibernateeexception:无法获得当前线程的事务同步会话。 自动布线和使用@服务可以完美地工作 我的单元测试课看起来像这样: @RunWith(SpringJUnit4ClassRunner.class)

在我的Spring Boot应用程序中,我访问我的Hibernate会话,如下所示:

现在我还想在单元测试中访问Hibernate会话

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

当我简单地自动连线它时,我得到
org.hibernate.hibernateeexception:无法获得当前线程的事务同步会话。

自动布线和使用
@服务
可以完美地工作

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

@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
        // ...

    }
}
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(类=App.class)
@网络集成测试
公共类网络测试{
@自动连线
私人会话工厂会话工厂;
@自动连线
私人用户服务;
@试验
公共void测试服务(){
最终列表用户=userService.getUsers();
//对用户做点什么
// ...
}
}

App.class
指的是使用main方法运行Spring Boot应用程序的类。

事实上,解决方案很简单,只需将
@Transactional
添加到测试类中即可

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