gorm-hibernate5
gorm-hibernate5 copied to clipboard
No Session found for current thread in spring boot test
When using @SpringBean in different SpringBootTest, spring will create a separate context for each test since spring doesn't know if those two tests share the same mock beans. This caused "No Session found for current thread" when running two tests together.
Please clone the following repo to reproduce it. [email protected]:ruiyang/gorm-spring-boot-hibernate-session-error.git or https://github.com/ruiyang/gorm-spring-boot-hibernate-session-error
There are two tests: VehicleServiceTest ManufacturerServiceTest
test passes when running each individually
./gradlew test --tests *ManufacturerServiceTest*
./gradlew test --tests *VehicleServiceTest*
test will fail when running together
./gradlew test
Please help! Thanks
Hi, By default, Spring shares the context across tests.
The @SpringBean annotation from Spock, as i understand it reading the documentation, modify the Spring Context, "preventing it from being reused by Spring’s outside of the current Specification".
To force the reload of the application context, you can use @org.springframework.test.annotation.DirtiesContext annotation to indicate that the context has been modified hope this helps
@jrechet Hi, thanks for looking into this. You are right and the DirtiesContext is what I'm using to workaround the issue. But I feel it is a workaround rather than a proper solution. It is fine for a project without many tests. If there are many tests, it will make the test run much slower. Could we investigate why restarting the spring context will cause this issue and if there is a better solution? Last time when I debugged it, I felt it was caused by adding those dynamic findBy or other dynamic methods to the GormEntity. Thanks