c# - .NET Core - 在集成测试中获取父程序集名称

标签 c# .net-core .net-assembly

我有一个集成测试项目,它使用 Microsoft.AspNetCore.TestHost 包托管在内存中。然后我有在这些测试中使用的库。我想从我的库获取测试项目的程序集名称。所以结构看起来像这样。

TestHost --> TestProject --> MyLibrary

我所做的是尝试调用以下方法:

Assembly.GetExecutingAssembly() 返回 MyLibrary 程序集

Assembly.GetCallingAssembly() 返回 MyLibrary 程序集

Assembly.GetEntryAssembly() 返回 TestHost 程序集。

有什么方法可以通过将程序集从 TestProject 传递到 MyLibrary 来获得它而无需明确指定它?

编辑

正如@svoychik 所建议的,我也尝试过直接从 TestProject 调用 MyLibrary 的方法中调用 Assembly.GetCallingAssembly() 但这会返回这个:

System.Private.CoreLib, Version=4.0.0.0, Culture=neutral,

最佳答案

根据 MSDN docs获取调用程序集:

Returns the Assembly of the method that invoked the currently executing method

因此,您只能在 TestProject 直接 调用的方法中检索调用程序集 TestProject。如果在另一部分代码中需要调用汇编,可以将其保存在一个变量中以供以后使用该值


例子: 假设你有 TestProject -> TestLibrary

测试项目

public class TestClass
    {
        public void TestWrite()
        {
            new ConsoleWriter().Write("hello world");
        }
    }

测试库

namespace TestLibrary
{
    public class ConsoleWriter
    {
        public void Write(string s)
        {
            Console.WriteLine(s);
            Console.WriteLine(System.Reflection.Assembly.GetCallingAssembly().GetName());
            Test();
        }

        private void Test()
        {
            Console.WriteLine("In test method");
            Console.WriteLine(System.Reflection.Assembly.GetCallingAssembly().GetName());
        }
    }
}

输出

hello world
TestProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
In test method
TestLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null

关于c# - .NET Core - 在集成测试中获取父程序集名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57022296/

相关文章:

c# - 如何在 C# 中以编程方式启动 apache 和 mysql 服务

c# - 如何使用 C# 安全地将数据保存到现有文件?

.Net Core VS2015,无法加载 DLL 'git2-785d8c4' : The specified module could not be found.(HRESULT 异常:0x8007007E)

c# - 调用 Microsoft.Owin.Cors 后无法加载 System.Web.Cors 程序集

c# - 程序集.Load .NET Core

c# - 升级具有 .NET 程序集依赖项的应用程序后出现严重的运行时错误

c# - 调整窗体大小时文本框大小发生变化

c# - Delphi dll函数转C#

c# - 关闭 websocket 最正确的方法是什么

windows - 为什么我无法运行 dotnet tool install --global bla-bla-bla?