Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6042165
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T06:45:36+00:00 2026-05-23T06:45:36+00:00

I have set up some In Memory SQLite Unit Tests for my Fluent NHibernate

  • 0

I have set up some In Memory SQLite Unit Tests for my Fluent NHibernate Database, which looks like this. It works fine. (Using NUnit)

namespace Testing.Database {
    /// <summary>
    /// Represents a memory only database that does not persist beyond the immediate
    /// testing usage, using <see cref="System.Data.SQLite"/>.
    /// </summary>
    public abstract class InMemoryDatabase : IDisposable {
        /// <summary>
        /// The configuration of the memorized database.
        /// </summary>
        private static Configuration Configuration { get; set; }

        /// <summary>
        /// The singleton session factory.
        /// </summary>
        protected static ISessionFactory SessionFactory { get; set; }

        /// <summary>
        /// The current session being used.
        /// </summary>
        protected ISession Session { get; set; }

        protected InMemoryDatabase() {
            SessionFactory = CreateSessionFactory();
            Session = SessionFactory.OpenSession();
            BuildSchema(Session);
        }

        /// <summary>
        /// Construct a memory based session factory.
        /// </summary>
        /// <returns>
        /// The session factory in an SQLite Memory Database.
        /// </returns>
        private static ISessionFactory CreateSessionFactory() {
            return FluentNHibernate.Cfg.Fluently.Configure()
            .Database(FluentNHibernate.Cfg.Db.SQLiteConfiguration
                .Standard
                .InMemory()
                .ShowSql())
            .Mappings(mappings => mappings.FluentMappings.AddFromAssemblyOf<Data.Mappings.AspectMap>())
            .ExposeConfiguration(configuration => Configuration = configuration)
            .BuildSessionFactory();
        }

        /// <summary>
        /// Builds the NHibernate Schema so that it can be mapped to the SessionFactory.
        /// </summary>
        /// <param name="Session">
        /// The <see cref="NHibernate.ISession"/> to build a schema into.
        /// </param>
        private static void BuildSchema(ISession Session) {
            var export = new NHibernate.Tool.hbm2ddl.SchemaExport(Configuration);
            export.Execute(true, true, false, Session.Connection, null);
        }

        /// <summary>
        /// Dispose of the session and released resources.
        /// </summary>
        public void Dispose() {
            Session.Dispose();
        }
    }
}

So now, in order to use it, I just inherit InMemoryDatabase and add my Test methods, like this.

[TestFixture]
    public class PersistenceTests : InMemoryDatabase {
        [Test]
        public void Save_Member() {
            var member = // ...;
            Session.Save(member); // not really how it looks, but you get the idea...
        }
    }

My problem isn’t that this doesn’t work. It does. But if I have two tests in the same class that test similar data, for instance …

Username_Is_Unique() and then Email_Is_Unique(). Not real tests again, but it’s a good example.

[Test]
public void Username_Is_Unique(){ 
   var user = new User { 
         Name = "uniqueName"
         Email = "uniqueEmail"
   };

   // do some testing here... 
}
[Test]
public void Email_Is_Unique(){ 
   var user = new User { 
         Name = "uniqueName"
         Email = "uniqueEmail"
   };

   // do some testing here... 
}

I realize these are very bad tests. These are not real tests, I am just citing an example.

In both cases, I would construct a mock User or Member or what-have you and submit it to the database.

The first one works fine, but since the database is in memory (which makes sense, since I told it to be), the second one doesn’t. Effectively, the Unit Tests do not reflect real-world situations, because each test stands alone. But when running them sequentially in a batch, it behaves like it should in the real world (I suppose that’s partially a good thing)

What I want to do is flush the in memory database after each method. So I came up with a simple way to do this by repeating the constructor. This goes in the InMemoryDatabase class.

protected void Restart() {
            SessionFactory = CreateSessionFactory();
            Session = SessionFactory.OpenSession();
            BuildSchema(Session);
        }

So now, in each method in my inheriting class, I call Restart() before I do my testing.

I feel like this isn’t the intended, or efficient way to solve my problem. Can anyone propose a better solution?

If it is of any relevance, I am using Fluent nHibernate for the persistence, and Telerik JustMock for my Mocking – but for my database stuff, I’ve yet to need any mocking.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-23T06:45:36+00:00Added an answer on May 23, 2026 at 6:45 am

    You need to drop and recreate the database for every test. Every test should be independent of the other. You can do do two thing, first have your test use a setup method (Assuming NUnit here but others have the same functionality)

        [SetUp]
        public void Setup()
        {
            // Create in memory database
            Memdb = new InMemoryDatabase();
        }
    

    Alternatively, you can wrap each test in a using statement for the database. For example

    [Test]
    public void Test()
    {
        using(var db = new InMemmoryDatabase())
        {
          Do Some Testing Here
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

No related questions found

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.