No, NHibernate's second-level (L2) cache does not automatically clear between integration tests if the same SessionFactory is reused.
The second-level cache is bound to the SessionFactory, not the Session. When using an in-memory SQLite database, the database data itself is wiped when the connection is closed, but the L2 cache provider (such as Ehcache or a simple in-memory map) remains in memory as long as the SessionFactory instance lives.
Key Behavior Rules
- Session Disposal: The cache survives the disposal of a session. Closing a session only clears the first-level (session) cache and returns the connection to the pool.
- Reopening Sessions: Closing and reopening a session does not clear the L2 cache. The new session will attempt to populate itself from the existing L2 entries.
- Factory Lifecycle: If your test suite creates a new
SessionFactory for every test, the cache is reset. If you use a singleton factory across tests, the cache persists, potentially leading to cross-test contamination.
How to Guarantee a Clean State
To prevent data leakage between tests while reusing the SessionFactory, you must manually evict the cache before or after each test. Use the following API calls:
// Clear all entries from the second-level cache
sessionFactory.Cache.Clear();
// Or clear entries for a specific entity type (recommended)
sessionFactory.Cache.EvictEntityData(typeof(MyEntity));
Assumptions and Uncertainties
This explanation assumes you are using a standard L2 cache provider configured in your NHibernate settings (e.g., cache.use_second_level_cache). A common point of confusion with SQLite in-memory is that the database itself disappears when the last connection closes. If your test setup closes the database connection between tests, the L2 cache might still contain "keys," but the underlying database data is gone, resulting in cache misses or errors when the next test tries to refresh the cache from the database.
Diagnostic Question: Are you using a single SessionFactory instance for the entire test suite, or are you recreating it for every test method?