You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@grails.apache.org by "jamesfredley (via GitHub)" <gi...@apache.org> on 2026/02/20 17:24:43 UTC
Re: [I] When I use @SpringBootTest it throws No Session found for current thread [grails-core]
jamesfredley commented on issue #12602:
URL: https://github.com/apache/grails-core/issues/12602#issuecomment-3936180512
This appears to be a Spring test context lifecycle issue rather than a GORM bug. When `@SpringBean` is used, Spock creates a separate Spring application context for each specification that uses different mock beans. However, GORM's static enhancer (which attaches dynamic finders, `withTransaction`, etc. to domain classes) retains a reference to the `SessionFactory` from the **first** context. When Spring creates a second context, that original `SessionFactory` has been closed, but the enhancer still points to it - causing "No Session found for current thread."
The fix is to annotate your test classes with `@DirtiesContext`, which tells Spring to close and recreate the application context after the test class runs, ensuring the next test gets a clean context with a fresh GORM enhancer binding:
```groovy
import org.springframework.test.annotation.DirtiesContext
@DirtiesContext
class VehicleServiceTest extends Specification {
@SpringBean
SomeService someService = Mock()
// ...
}
@DirtiesContext
class ManufacturerServiceTest extends Specification {
@SpringBean
AnotherService anotherService = Mock()
// ...
}
```
This ensures each test specification gets its own fully initialized context with a properly bound GORM `SessionFactory`. The tradeoff is slightly slower test execution since contexts aren't cached across specs, but it's the correct approach when `@SpringBean` modifies the context.
Alternatively, if you can share the same set of mock beans across tests, put them in a common base class or use `@ContextConfiguration` with a shared config - that way Spring can reuse the context without conflict.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@grails.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org