在程序集外部访问内部构造函数

Access internal constructor outside the assembly

我查看了github中Specflow的代码,发现了一个棘手的问题,我无法理解。

https://github.com/SpecFlowOSS/SpecFlow/blob/master/TechTalk.SpecFlow/ScenarioContext.cs

中的第 69 行
internal ScenarioContext(IObjectContainer scenarioContainer, ScenarioInfo scenarioInfo, ITestObjectResolver testObjectResolver)

https://github.com/SpecFlowOSS/SpecFlow/blob/master/Tests/TechTalk.SpecFlow.PluginTests/Infrastructure/WindsorPluginTests.cs

中的第 97~100 行
            var context = new ScenarioContext(
                objectContainer.Object, 
                new ScenarioInfo("", "", Array.Empty<string>(), new OrderedDictionary()), 
                new WindsorTestObjectResolver());

TechTalk.SpecFlow.ScenarioContext的构造函数是内部的,这意味着它只能在TechTalk.SpecFlow.dll中访问。为什么在TechTalk.SpecFlow.PluginTests.Infrastructure.WindsorPluginTestsclass还能访问? TechTalk.SpecFlow.PluginTests.Infrastructure.WindsorPluginTests class 在 TechTalk.SpecFlow.PluginTests.dll 中。他们在不同的程序集。

因为InternalsVisibleTo。这使得从授权程序集调用的每个对象都可以访问内部类型、方法等。

https://github.com/SpecFlowOSS/SpecFlow/blob/master/TechTalk.SpecFlow/AssemblyAttributes.cs 中,程序集 TechTalk.SpecFlow 装饰有一些这样的属性,将所有内部方法暴露给列出的程序集:

  • TechTalk.SpecFlow.RuntimeTests
  • TechTalk.SpecFlow.PluginTests

这是一种非常常见且有用的技术,用于测试任何人都不应该访问但需要测试的方法。