简体   繁体   中英

What is wrong with this set up for unit tests using nhibernate and an in-memory sqlite db?

I have an app written in c# using nhibernate with an sqlite DB. For unit testing, I'm using xunit and an in-memory sqlite db.

I'm aware that the in-memory DB is destroyed when the session is closed so for testing, I use a single session and keep it open for the duration of the test. In most of my tests this works fine.

However, in a few cases, I need to test methods that make use of both ISession and IStatelessSession . After a little research, I settled on something similar to the approach described here . So the IStatelessSession is created using the ISession 's connection like this:

statelessSession = factory.OpenStatelessSession(existingSession.Connection);

The problem is that this seems to cause some sort of conflict as soon as a change is persisted to the DB. If I do a transaction with session.SaveOrUpdate(new Entity() {...}) then that's fine but if I then do a statelessSession.Get<Entity>(1) then it will fail with the error message "collection is not associated with any session".

Normally, this error would indicate that the session is closed, but in this case, both sessions are still open and active.

If I do session.Get<Entity>(1) then it returns the entity as expected. Initially, I thought this might be because the session and stateless session were somehow out of sync so I replaced session.SaveOrUpdate.. with statelessSession.Insert(new Entity() {...}) and reran the test. Strangely, this made no difference. The regular session still works fine and the statelessSession is still broken.

Finally, I've found a solution to this whole thing:

Eventually, I went back to my original query (a more complex query than the example above that returns multiple results) and tried various things while debugging through it, none of which shed any light on the problem. I then decided to remove the 'where' part of that query to see if it made any difference. Strangely, it did. It still failed, but this time I got a different exception: 'could not execute query', this also had an inner exception: 'possible non-threadsafe access to the session'.

The whole test runs on a single thread and I confirmed this by looking at the thread view when debugging. So I thought I'd hit another brick wall. However, after some googling, I found this blog post that describes the same problem and the solution: just update to the latest version of nhibernate!

I updated from 3.1.0 to 3.3.1 (thanks to NUGet, this was a breeze) re ran the test and it worked. Put the where clause back and the test passed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM