创建类访问器的实例

Chr*_*ian 5 .net c# unit-testing vs-unit-testing-framework

我目前正在编写一个单元测试框架,它最终将运行用Visual Studio编写的标准单元测试.框架目前无法正常使用访问者.请考虑以下测试方法:

[TestMethod()]
public void TestMethod()
{
      ExampleMethods_Accessor target = null;
      target = new ExampleMethods_Accessor();
      target.SomeMethod();
}
Run Code Online (Sandbox Code Playgroud)

在此示例中,访问者已由Visual Studio生成.使用Visual Studio的单元测试环境运行时,单元测试工作正常.但是,我想从我的框架内调用TestMethod().在"target = new ExampleMethods_Accessor()"行中,抛出以下异常:

"Proband.ExampleMethods_Accessor"的类型初始化程序引发了一个例外.

内部异常:

无法加载文件或程序集:Proband,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null ...

有谁知道微软单元测试框架如何调用单元测试?我在想它可能是由于缺少TestContext对象.在我的情况下,这是"空".在Visual Studio中启动单元测试时,TestContext对象包含大量信息.可能是,我需要正确地初始化它吗?怎么需要初始化?

谢谢你的帮助,克里斯蒂安

编辑:

我一直在试验访问者的工作方式.我使用ILSpy来查看Proband_Accessor.dll中生成了什么代码.事实证明导致异常的指令是:

SomeClass_Accessor.m_privateType = new PrivateType("Probant, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "Probant.SomeClass");
Run Code Online (Sandbox Code Playgroud)

我将我的单元测试代码修改为这样(仅用于测试):

    [TestMethod()]
    [DeploymentItem("Proband.dll")]
    public void SomeMethodTest()
    {
        ExampleMethods_Accessor target = null;
        ExampleMethods c = null;

        try
        {
            Assembly.Load("Proband, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"); // this works fine
            PrivateType tx = new PrivateType(typeof(ExampleMethods)); // this works fine as well (also without loading the assembly)

            PrivateType t = new PrivateType("Proband, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "Proband.ExampleMethods"); // this causes the exception

            c = new ExampleMethods(); // this works fine
            target = new ExampleMethods_Accessor(); // this causes the exception as well
        }
        catch (Exception ex)
        {
            Console.WriteLine();
        }
        int actual;
        actual = target.SomeMethod();
    }
Run Code Online (Sandbox Code Playgroud)

我完全不明白,为什么"新的PrivateType("Proband,Version ...."不起作用.有人有想法吗?

Chr*_*ian 1

我已经设法为该问题创建一个解决方法。

在我的 AppDomain 中,我添加了一个 AssemblyResolveEventHandler:

    AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);
Run Code Online (Sandbox Code Playgroud)

该事件处理程序包含以下代码:

    private Assembly MyResolveEventHandler(object sender, ResolveEventArgs args)
    {
        if(args.Name == "Proband, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null")
        {
            // resolving correct assembly of type under test
            return typeof(ExampleMethods).Assembly;
        }
        else
        {
            return null;
        }
    }
Run Code Online (Sandbox Code Playgroud)

现在代码行“target = new ExampleMethods_Accessor();” 工作正常并返回正确的访问器对象。

我还是不明白,为什么大会不能自动解决。

即使任何人都不太可能遇到同样的问题:我希望这个答案可以帮助某人:)