创建类访问器的实例

发布于 2024-12-09 14:36:07 字数 2072 浏览 5 评论 0 原文

我目前正在编写一个单元测试框架,该框架最终将运行在 Visual Studio 中编写的标准单元测试。该框架目前无法与访问器一起正常工作。考虑以下测试方法:

[TestMethod()]
public void TestMethod()
{
      ExampleMethods_Accessor target = null;
      target = new ExampleMethods_Accessor();
      target.SomeMethod();
}

在本例中,访问器是由 Visual Studio 生成的。使用 Visual Studio 的单元测试环境运行时,单元测试工作得非常好。但是,我想从我的框架内调用 TestMethod()。在“target = new ExampleMethods_Accessor()”行,引发以下异常:

“Proband.ExampleMethods_Accessor”的类型初始值设定项引发异常。

内部异常:

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

有人知道 Microsoft 单元测试框架如何调用单元测试吗?我认为这可能是由于缺少 TestContext 对象造成的。在我的例子中这是“null”。在 Visual Studio 中启动单元测试时,TestContext 对象包含大量信息。难道我需要正确初始化它吗?需要如何初始化?

感谢大家的帮助, Christian

编辑:

我一直在尝试访问器的工作方式。我使用 ILSpy 查看 Proband_Accessor.dll 中生成了哪些代码。事实证明,导致异常的指令是:

SomeClass_Accessor.m_privateType = new PrivateType("Probant, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "Probant.SomeClass");

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

    [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();
    }

我完全不明白,为什么“new PrivateType(”Proband, Version....”不起作用有谁有想法吗?

I am currently writing a unit test framework which shall in the end run standard unit tests written in Visual Studio. The Framework is currently not working correctly with accessors. Consider the following test method:

[TestMethod()]
public void TestMethod()
{
      ExampleMethods_Accessor target = null;
      target = new ExampleMethods_Accessor();
      target.SomeMethod();
}

In this example, the accessor has been generated by Visual Studio. The unit test works perfectly fine when run using the Unit Testing environment of Visual Studio. However, I would like to invoke the TestMethod() from within my Framework. At the line "target = new ExampleMethods_Accessor()", the following exception is thrown:

The type initializer for "Proband.ExampleMethods_Accessor" threw an excepition.

Inner exception:

Could not load file or assembly: Proband, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null...

Has anyone an idea of how the Microsoft Unit Testing Framework invokes unit tests? I was thinking it might be due to the missing TestContext object. This is "null" in my case. When starting the unit test in Visual Studio, the TestContext object contains a lot of information. Could it be, that I need to initialize it properly? How would it need to be initialized?

Thanks for all help,
Christian

EDIT:

I kept experimenting with the way accessors are working. I used ILSpy to see what code is being generated into the Proband_Accessor.dll. It turns out that the instruction causing the exception is:

SomeClass_Accessor.m_privateType = new PrivateType("Probant, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "Probant.SomeClass");

I modified my unit test code to be like this (just for test):

    [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();
    }

I do absolutely not understand, why "new PrivateType("Proband, Version...." does not work. Has anyone an idea?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

飞烟轻若梦 2024-12-16 14:36:07

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

对于我的 AppDomain,我添加了一个 AssemblyResolveEventHandler:

    AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);

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

    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;
        }
    }

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

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

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

I have managed to create a workaround for the issue.

To my AppDomain, I am adding an AssemblyResolveEventHandler:

    AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);

This event handler contains the following code:

    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;
        }
    }

Now the line of code "target = new ExampleMethods_Accessor();" works fine and returns the correct accessor object.

I still do not understand, why the Assembly cannot be resolved automatically.

Even if it is very unlikely that anyone will have the same problem: I hope this answer helps someone :)

童话里做英雄 2024-12-16 14:36:07

我没有做任何复杂的事情,但我有:

  1. 使用 .NET 3.5 的 Web 应用程序项目
  2. 使用 .NET 3.5 的配置
  3. 项目 使用 .NET 3.5 的测试项目

在尝试使用访问器运行单元测试时,我遇到了相同的 BadImageFormat 异常。

我找到了以下链接:

http://connect.microsoft.com/VisualStudio/feedback/details/677203/even-after-installing-vs2010-sp1-unit-tests-targeting-3-5-framework-fail-if-他们-正在使用-private-accessor#details

第二个解决方法解决了我的问题。我将测试项目更改为针对 .NET 4.0,并且它有效。

I am not doing anything nearly as complex, but I had:

  1. web application project using .NET 3.5
  2. Configuration project using .NET 3.5
  3. Test project using .NET 3.5

I was getting the same BadImageFormat exception when trying to run a unit test using an accessor.

I found the following link:

http://connect.microsoft.com/VisualStudio/feedback/details/677203/even-after-installing-vs2010-sp1-unit-tests-targeting-3-5-framework-fail-if-they-are-using-private-accessor#details

The second work-around solved my problem. I changed the test project to target .NET 4.0 and it worked.

年华零落成诗 2024-12-16 14:36:07

我刚刚遇到了这个问题,这是因为我从测试方法中删除了 DeploymentItem 属性。再次添加后,构建机器上不再出现错误。

[TestMethod]
[DeploymentItem("FedImportServer.dll")]  // ** This is necessary for the build machine. **
public void SourceFileStillExistsAfterProcessingFails()

注意:我在本地运行时从未遇到过错误。

这是错误:

测试方法 FedImportTests.FedImportServiceHostTest.FileNoLongerExistsAfterSucessfulProcessing 引发异常:
System.TypeInitializationException:“FedImportServer.Processing.FileProcessor_Accessor”的类型初始值设定项引发异常。 ---> System.IO.FileNotFoundException:无法加载文件或程序集“FedImportServer,Version=1.0.0.0,Culture=neutral,PublicKeyToken=null”或其依赖项之一。系统找不到指定的文件。

I just had this exact problem, and it was because I removed the DeploymentItem attribute from the test method. Once I added it again, I no longer got the error on the build machine.

[TestMethod]
[DeploymentItem("FedImportServer.dll")]  // ** This is necessary for the build machine. **
public void SourceFileStillExistsAfterProcessingFails()

Note: I never got the error when running it locally.

This is the error:

Test method FedImportTests.FedImportServiceHostTest.FileNoLongerExistsAfterSucessfulProcessing threw exception:
System.TypeInitializationException: The type initializer for 'FedImportServer.Processing.FileProcessor_Accessor' threw an exception. ---> System.IO.FileNotFoundException: Could not load file or assembly 'FedImportServer, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文