You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让XUnit测试项目从指定文件夹加载C#项目引用?

解决xUnit测试中从指定文件夹加载.NET Framework程序集的问题

针对你的场景(.NET Framework 4.8项目,xUnit测试需要从C:\runtime\加载大量不复制到输出目录的依赖DLL),可以采用以下几种方案:

方案1:利用AppDomain程序集解析事件 + xUnit集合夹具

通过注册AppDomain.AssemblyResolve事件,在CLR找不到程序集时自动从指定目录查找,结合xUnit的集合夹具实现全局生效,无需逐个配置依赖。

步骤1:创建全局程序集解析夹具

using System;
using System.Linq;
using System.Reflection;
using Xunit;

public class RuntimeAssemblyResolverFixture : IDisposable
{
    public RuntimeAssemblyResolverFixture()
    {
        AppDomain.CurrentDomain.AssemblyResolve += ResolveRuntimeAssembly;
    }

    private Assembly ResolveRuntimeAssembly(object sender, ResolveEventArgs args)
    {
        var assemblyName = new AssemblyName(args.Name);
        var targetPath = $"C:\\runtime\\{assemblyName.Name}.dll";

        // 优先直接查找根目录
        if (System.IO.File.Exists(targetPath))
        {
            return Assembly.LoadFrom(targetPath);
        }

        // 递归查找子目录(如果需要)
        var subDirPath = System.IO.Directory.EnumerateFiles(
            "C:\\runtime", 
            $"{assemblyName.Name}.dll", 
            System.IO.SearchOption.AllDirectories
        ).FirstOrDefault();

        return string.IsNullOrEmpty(subDirPath) ? null : Assembly.LoadFrom(subDirPath);
    }

    public void Dispose()
    {
        AppDomain.CurrentDomain.AssemblyResolve -= ResolveRuntimeAssembly;
    }
}

// 定义测试集合,绑定夹具
[CollectionDefinition("RuntimeAssemblyResolverCollection")]
public class RuntimeAssemblyResolverCollection : ICollectionFixture<RuntimeAssemblyResolverFixture>
{
    // 无需实现任何成员,仅用于标记集合
}

步骤2:在测试类中启用夹具

在需要加载runtime依赖的测试类上添加集合特性:

[Collection("RuntimeAssemblyResolverCollection")]
public class Dialog1ViewModelTests
{
    [Fact]
    public void TestViewModelInitialization()
    {
        // 测试逻辑,此时CLR会自动从C:\runtime加载依赖
    }
}

方案2:修改测试项目app.config配置(仅适用于特定场景)

如果依赖路径是相对测试输出目录的,可以通过probing节点指定私有路径;但针对绝对路径C:\runtime\,需要逐个配置codebase(不推荐用于大量DLL的场景):

<configuration>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <!-- 单个程序集的绝对路径配置示例 -->
      <dependentAssembly>
        <assemblyIdentity name="X.Y.Z.Forms.Wpf" publicKeyToken="你的公钥令牌" culture="neutral"/>
        <codebase version="1.0.0.0" href="file:///C:\runtime\X.Y.Z.Forms.Wpf.dll"/>
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

注意:这种方式需要为每个依赖DLL手动配置,对于20+个对话框的场景,维护成本极高,因此优先推荐方案1。

方案说明

xUnit本身没有类似MSTest .runsettings中AssemblyResolution的内置配置,因此需要借助CLR的程序集解析机制来实现自定义加载逻辑。方案1的集合夹具可以确保所有测试类共享同一套解析规则,无需重复代码,且能自动处理子目录中的依赖。

内容的提问来源于stack exchange,提问作者fx999dev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 12:53:39