NUnit NHibernate and Moq unit test throwing NHibernate.MappingException

366 views Asked by At

I'm using Ayende's code from his blog on unit testing with NHibernate and it calls for testing with SQLite, code as follows:

using System;
using System.Reflection;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Dialect;
using NHibernate.Driver;
using NHibernate.Tool.hbm2ddl;
using Environment = NHibernate.Cfg.Environment;

namespace WebAPI.Tests
{
    /// <summary>
    /// http://ayende.com/blog/3983/nhibernate-unit-testing
    /// </summary>
    public class InMemoryDatabaseTest : IDisposable
    {
        private static Configuration _configuration;
        private static ISessionFactory _sessionFactory;
        protected ISession Session;

        public InMemoryDatabaseTest(Assembly assemblyContainingMapping)
        {
            if (_configuration == null)
            {
                _configuration = new Configuration()
                    .SetProperty(Environment.ReleaseConnections, "on_close")
                    .SetProperty(Environment.Dialect, typeof(SQLiteDialect).AssemblyQualifiedName)
                    .SetProperty(Environment.ConnectionDriver, typeof(SQLite20Driver).AssemblyQualifiedName)
                    .SetProperty(Environment.ConnectionString, "data source=:memory:")
                    .AddAssembly(assemblyContainingMapping);

                _sessionFactory = _configuration.BuildSessionFactory();
            }

            Session = _sessionFactory.OpenSession();

            new SchemaExport(_configuration).Execute(false, true, false);
        }

        public void Dispose()
        {
            Session.Dispose();
        }
    }
}

My test class is:

[TestFixture]
public class FilmsControllerTests : InMemoryDatabaseTest
{
    public FilmsControllerTests() : base(typeof(Film).Assembly)
    {
    }

    static readonly Guid ValidFilmId = new Guid("35d3ee0f5ee011bd8822ed629e5");

    [Test]
    public void CanSaveAndLoadFilm()
    {
        object id;

        using (var tx = Session.BeginTransaction())
        {
            id = Session.Save(new PdfFilm
            {
                IsEnabled = true,
                Id = ValidFilmId,
                PremiumLevel = 1,
                PublishDate = new DateTime(20121010),
                Pdf = new Document(new byte[byte.Parse(" 162")], new DateTime(20121010)),
                Title = "jel",
                Authors = "smel",

            });

            tx.Commit();
        }

        Session.Clear();


        using (var tx = Session.BeginTransaction())
        {
            var Film = Session.Get<PdfFilm>(id);

            Assert.AreEqual(new DateTime(2012, 10, 10), Film.PublishDate);

            tx.Commit();
        }
    }

And Model:

public abstract class Film : Entity<Film>

Which has a nested class:

public class PdfFilm: Film

And starts it's mapping config in the same file as the parent as:

<subclass name="PdfFilm" discriminator-value="Pdf">

The NUnit unit test returns:

NHibernate.MappingException : No persister for: Core.PdfFilm

I've checked the properties of the Film mapping file and it's set as embedded resource - could anyone please also confirm if this is the simplest way of testing and also any idea what the error message means?

Stack trace:

at NHibernate.Impl.SessionFactoryImpl.GetEntityPersister(String entityName)
at NHibernate.Impl.SessionImpl.GetEntityPersister(String entityName, Object obj)
at NHibernate.Event.Default.AbstractSaveEventListener.SaveWithGeneratedId(Object entity, String entityName, Object anything, IEventSource source, Boolean requiresImmediateIdAccess)
at NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.SaveWithGeneratedOrRequestedId(SaveOrUpdateEvent event)
at NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.EntityIsTransient(SaveOrUpdateEvent event)
at NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.OnSaveOrUpdate(SaveOrUpdateEvent event)
at NHibernate.Impl.SessionImpl.FireSave(SaveOrUpdateEvent event)
at NHibernate.Impl.SessionImpl.Save(Object obj)
1

There are 1 answers

1
Radim Köhler On

This error is always reporting about one issue: NHibernate configuration, used to build ISessionFactory - did not received the expected mapping. Here is a detailed overview what all we must to check to be sure that xml mapping file will be used:

The most important three things to check (and almost always solution):

  • xml mapping file is NOT makred as Embedded Resource
  • xml file is not part of .dll which is configured as the mapping source <mapping assembly="MyProject.Data" /> (see <session-factory> configuration) (in case above, be sure that the mapping is part of the assembly passed into: AddAssembly(assemblyContainingMapping))
  • xml file does not have the default suffix .hbm.xml