2

I have a solution with two projects within:

Company.Project.vbproj
Company.Project.Tests.vbproj

Within the Company.Project.vbproj assembly, I have a class FriendClass.vb which scope is Friend (internal in C#).

Now I wish to test this FriendClass.vb from within the Company.Project.Tests.vbproj assembly. I know about the InternalsVisibleToAttribute, but that is not an option in Visual Basic .NET 2.0, as it is only available with C#, in .NET 2.0 (see here).

I would like to create myself a proxy class using this internal FriendClass from within my testing assembly, so that I could instantiate it and do the testings accordingly.

Any idea or known practices to do so?

Thanks in advance! =)

4

1 回答 1

1

我发现的唯一解决方法是在 .NET Framework 1.1 中使用过的一种。

由于InternalsVisibleToAttribute在 .NET 2.0 Visual Basic 中不可用,我发现的唯一解决方法是将我的测试包含在与我的库本身相同的项目中。此外,还需要完成一些进一步的工作。

  1. 为自己创建一个名为“Tests”的新编译配置(您可以在其中选择“Release”/“Debug”);
  2. 在您的项目中创建一个名为“Tests”的新文件夹;
  3. 添加一个新类,用于测试您的 Friend(C# 内部)成员;
  4. 此类中的第一行代码应该是#if CONFIG = "Tests" then ... #end if
  5. 将您的代码放在此编译器 IF 指令之间。

例如,如果我有以下 Friend 类:

Friend Class MyFactory
    Friend Property Property1 As Object
        Get
            Return _field1
        End Get
        Set (ByVal value As Object)
            _field1 = value
        End Set
    End Property

    Friend Sub SomeSub(ByVal param1 As Object)
        ' Processing here...
    End Sub
End Class

然后,如果您想在 .NET 2.0 Visual Basic 中测试这个类,您需要在MyFactory该类所在的同一个项目中创建一个测试类。这个类应该是这样的:

#If CONFIG = "Tests" Then

    Imports NUnit.Framework

    <TestFixture()> _
    Public Class MyFactoryTests
        <Test()> _
        Public Sub SettingProperty1Test
            ' Doing test here...
        End Sub
    End Class

#End If

由于您有一个编译器指令告诉编译器仅在选择“测试”配置时才编译并包含此类,因此您不会在“调试”或“发布”模式下获得此类。这个类甚至不会成为库的一部分,因为它不会不必要地污染你的库,这让你无论如何都可以测试你的 Friend 类。

这是我发现在 Visual Basic .NET 2.0 中解决此问题的最聪明的方法。

于 2010-09-23T17:51:56.593 回答