Home > Blockchain >  Access internal constructor outside the assembly
Access internal constructor outside the assembly

Time:03-10

I reviewed the code of Specflow in github and found a tricky issue that I cannot understand.

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

internal ScenarioContext(IObjectContainer scenarioContainer, ScenarioInfo scenarioInfo, ITestObjectResolver testObjectResolver)

Line 97~100 in https://github.com/SpecFlowOSS/SpecFlow/blob/master/Tests/TechTalk.SpecFlow.PluginTests/Infrastructure/WindsorPluginTests.cs

            var context = new ScenarioContext(
                objectContainer.Object, 
                new ScenarioInfo("", "", Array.Empty<string>(), new OrderedDictionary()), 
                new WindsorTestObjectResolver());

The constructor of TechTalk.SpecFlow.ScenarioContext is internal which means it could only access in the TechTalk.SpecFlow.dll. Why it still can access in TechTalk.SpecFlow.PluginTests.Infrastructure.WindsorPluginTests class? TechTalk.SpecFlow.PluginTests.Infrastructure.WindsorPluginTests class is in TechTalk.SpecFlow.PluginTests.dll. They are in different assembly.

CodePudding user response:

Because of InternalsVisibleTo. This enables access to internal types, methods, etc. to every object calling from the authorized assembly.

In https://github.com/SpecFlowOSS/SpecFlow/blob/master/TechTalk.SpecFlow/AssemblyAttributes.cs the assembly TechTalk.SpecFlow is decorated with some of this attributes, exposing all the internal methods to the listed assemblies:

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

It's a very common and useful technique used to test methods that should not be accessible to anyone, but that need to be tested.

  • Related