Reputation: 14551
In my Spring Boot application I access my Hibernate session as shown in this answer: https://stackoverflow.com/a/33881946/272180
Now I also want to access the Hibernate Session in a unit test.
How can I set up the datasource and access the Hibernate Session in a unit test of a Spring Boot application?
When I simply Autowire it, I get org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread.
Autowiring and using a @Service
works flawlessly.
My unit-testing class looks like this 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
refers to the class with the main method which is used to run the Spring Boot application.
Upvotes: 4
Views: 5566
Reputation: 14551
In fact, the solution was as easy as adding @Transactional
to the test-class.
After that I could use the SessionFactory
as usual.
Upvotes: 5