简体   繁体   中英

NHibernate: How to reference the assembly of the main project from the unit test project?

I built a simple NHibernate Application but i wanted to use Mapping Attributes instead of Mapping XML.

Now i have the problem, when i create a Unit Test Project and want to load the Mapping Attributes, that my domain objects are in the other project!

This is my Unit Test:

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;

namespace Tests
{
[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void TestMethod1()
    {
        Configuration cfg = new Configuration();
        cfg.Configure();
        cfg.AddInputStream(NHibernate.Mapping.Attributes.HbmSerializer.Default.Serialize(
            System.Reflection.Assembly.GetExecutingAssembly()));
        new SchemaExport(cfg).Execute(false, true, false);
    }
}

In this line

cfg.AddInputStream(NHibernate.Mapping.Attributes.HbmSerializer.Default.Serialize(
            System.Reflection.Assembly.GetExecutingAssembly()));

I get this Exception:

Result Message: 
Test method Tests.UnitTest1.TestMethod1 threw exception: 
NHibernate.Mapping.Attributes.MappingException: The following assembly contains 
no mapped classes: Tests, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
Result StackTrace:  
at NHibernate.Mapping.Attributes.HbmSerializer.Serialize(Stream stream, Assembly assembly)
   at NHibernate.Mapping.Attributes.HbmSerializer.Serialize(Assembly assembly)
   at Tests.UnitTest1.TestMethod1() in ...Tests\UnitTest1.cs:Line 17.

I guess instead of

System.Reflection.Assembly.GetExecutingAssembly()

I have to get somehow the assembly of my main project.

I found the easiest way to do this was with:

Assembly.Load("Project Name of Desired Assembly")

I read a lot of stuff online to do this, including this post, and nothing was more simple than using this method. Also, the methods mentioned by JoelC probably work, however I couldn't get them to work for me and this worked no problems.

Yeah, calling System.Reflection.Assembly.GetExecutingAssembly() from unit tests usually will give you the unit test runner as the executing assembly.

You should be able to call typeof([TargetAssemblyClass]).Assembly to find your main project assembly. This, of course, requires a reference to the main project which I expect you already have.

Edit: Calling System.Reflection.Assembly.GetAssembly(typeof([TargetAssemblyClass])) is another way to achieve the same thing.

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