在NUnit测试中创建App域的异常

时间:2014-06-23 12:44:41

标签: c# unit-testing plugins nunit appdomain

我编写了一个插件库,用于在目录中搜索导出给定接口实现的程序集。它通过将所有程序集加载到仅反射上下文中的临时应用程序域并搜索导出的类型来实现此目的。然后卸载临时应用程序域,将感兴趣的程序集加载到默认应用程序域中,然后实例化找到的类型的对象,以便通过搜索的界面使用。

我正在尝试使用NUnit为这个进程编写一些单元测试,但是当我尝试连接ReflectionOnlyAssemblyResolve事件时,我只在单元测试中得到一个FileNotFoundException。这是一个简单的例子:

using System;
using System.Reflection;
using NUnit.Framework;

namespace NUnitAppDomains
{
    [TestFixture]
    public class TestClass
    {
        [Test]
        public void NUnitTest()
        {
            var ad = AppDomain.CreateDomain("someName");

            // this next line throws a FileNotFoundException, complaining about not being 
            // able to find the test assembly itself... o.O
            ad.ReflectionOnlyAssemblyResolve += SomeHandler;

            AppDomain.Unload(ad);
        }

        static Assembly SomeHandler(object sender, ResolveEventArgs args)
        {
            // some code would be here

            throw new NotImplementedException();
        }
    }
}

我试图在已知位置的某些虚拟装配上测试代码,其中一些虚拟装配包含/不包含有效的imlementation / s。我的代码是否不适合单元测试,或者如果是,我该如何避免这些异常?感谢

1 个答案:

答案 0 :(得分:3)

问题是您的代码在不同的应用程序库中运行(NUnit或Visual Studio或运行测试的任何内容)。在未指定基础的情况下创建域时,它使用运行代码的应用程序的基础,例如“Program Files \ NUnit \ Bin”,当然你的装配在那里找不到。

解决方案是在创建AppDomain时使用代码的应用程序库,您可以从当前线程获取:

var callingDomain = Thread.GetDomain();
var setup = new AppDomainSetup 
            { 
                ApplicationBase = callingDomain.SetupInformation.ApplicationBase 
            };

var ad = AppDomain.CreateDomain("someName", null, setup);

This blog post更详细一些,但并不多。仍然值得一读。