访问通过的System.Reflection内部成员?成员、System、Reflection

2023-09-02 11:56:14 作者:新生

我试图单元测试,有很多内部功能的类。这显然​​需要测试过,但我的测试项目是独立的,主要是因为它涵盖了许多小的,相关的项目。我至今是:

I'm trying to Unit Test a class that has many internal functions. These obviously need testing too, but my Tests project is seperate, mainly because it covers many small, related projects. What I have so far is:

FieldInfo[] _fields = 
    typeof(ButtonedForm.TitleButton).GetFields(
        BindingFlags.NonPublic | BindingFlags.Instance | 
        BindingFlags.DeclaredOnly);
Console.WriteLine("{0} fields:", _fields.Length);
foreach (FieldInfo fi in _fields)
{
    Console.WriteLine(fi.Name);
}

本吐出所有的私有成员很好,但还是不显示内部。我知道这是可能的,因为当我插科打诨与自动生成的测试,Visual Studio中可以产生,它询问是与显示内部的测试项目。好了,现在我使用NUnit的,真正喜欢它,但我怎么能做到同样的事情呢?

This spits out all the private members nicely, but still doesn't display internals. I know this is possible, because when I was messing around with the autogenerated tests that Visual Studio can produce, it asked about something to do with displaying internals to the Test project. Well, now I'm using NUnit and really liking it, but how can I achieve the same thing with it?

推荐答案

这将是更适合使用的InternalsVisibleTo属性授予你的单元测试组件访问组件的内部成员。

It would be more appropriate to use the InternalsVisibleTo attribute to grant access to the internal members of the assembly to your unit test assembly.

下面是一些有用的附加信息的链接,并通过散步:

Here is a link with some helpful additional info and a walk through:

中InternalsVisibleTo的奇迹

要真正回答你的问题......内部和保护未在.NET反射API的认可。下面是从 MSDN 报价:

To actually answer your question... Internal and protected are not recognized in the .NET Reflection API. Here is a quotation from MSDN:

C#的关键字保护,并且内部具有的IL没有意义,没有在反射API一起使用。在IL相应的条款是家庭和装配。要使用反射识别内部方法,使用IsAssembly属性。要确定一个受保护的内部方法,使用IsFamilyOrAssembly.

The C# keywords protected and internal have no meaning in IL and are not used in the Reflection APIs. The corresponding terms in IL are Family and Assembly. To identify an internal method using Reflection, use the IsAssembly property. To identify a protected internal method, use the IsFamilyOrAssembly.