开发者

How to use reflection to unit-test an internal (Friend in VB) class within an assembly, when the InternalsVisibleToAttribute is not an option?

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 Basi开发者_StackOverflow社区c .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! =)


The only workaround that I have found is one used back in .NET Framework 1.1.

As the InternalsVisibleToAttribute is not useable in .NET 2.0 Visual Basic, the only workaround that I have found is to include my tests within the same project as my library itself. Besides, some further work needs to be accomplished.

  1. Create yourself a new compilation CONFIG called "Tests" (that is where you may select "Release"/"Debug");
  2. Create a new folder named "Tests" within your project;
  3. Add a new class, the one to test your Friend (internal in C#) members;
  4. First line of code within this class should be: #if CONFIG = "Tests" then ... #end if;
  5. Place your code between this compiler IF directive.

For example, if I have the following Friend class:

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

Then, if you want to test this class in .NET 2.0 Visual Basic, you will need to create a test class within the same project where the MyFactory class sits. This class should look like so:

#If CONFIG = "Tests" Then

    Imports NUnit.Framework

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

#End If

Since you have a compiler directive telling the compiler to compile and to include this class only when the "Tests" CONFIG is selected, you won't get this class on "Debug" or on "Release" mode. This class won't even be part of the library, this for not polluting your library unnecessarily, and this allows you to test your Friend class anyway.

That is the smartest way I have found to work around this issue in Visual Basic .NET 2.0.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜