这是我每次编写 Nsubstitute Excel 单元测试时对自己的一个提醒。我已经与这个错误作斗争太多次了。
您将收到错误:无法对空引用执行运行时绑定
引用 .Net Excel 对象库后,必须引用 COM Microsoft Excel 14.0 对象库。引用 COM interop Excel DLL 后,单击 F4 以查看 DLL 属性,记住将 COM Interop NOT 设置为 Embed Interop Types。
.Excel 这是一个工作项目文件:
<ItemGroup>
<Reference Include="Microsoft.Office.Interop.Excel.Extensions">
<HintPath>..\..\Refs\Microsoft.Office.Interop.Excel.Extensions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" />
<Reference Include="NSubstitute">
<HintPath>..\..\Refs\NSubstitute.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Data" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Runtime.Serialization" />
<Reference Include="System.Xml" />
<Reference Include="System.Xml.Linq" />
<Reference Include="UIAutomationProvider" />
<Reference Include="VSTOContrib.Core, Version=0.9.0.52, Culture=neutral, processorArchitecture=MSIL" />
<Reference Include="WindowsBase" />
<Reference Include="WindowsFormsIntegration" />
</ItemGroup>
<ItemGroup>
<CodeAnalysisDependentAssemblyPaths Condition=" '$(VS100COMNTOOLS)' != '' " Include="$(VS100COMNTOOLS)..\IDE\PrivateAssemblies">
<Visible>False</Visible>
</CodeAnalysisDependentAssemblyPaths>
</ItemGroup>
<ItemGroup>
<Compile Include="MockFactory.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="UnitTests.cs" />
</ItemGroup>
<ItemGroup>
<COMReference Include="Microsoft.Office.Core">
<Guid>{2DF8D04C-5BFA-101B-BDE5-00AA0044DE52}</Guid>
<VersionMajor>2</VersionMajor>
<VersionMinor>4</VersionMinor>
<Lcid>0</Lcid>
<WrapperTool>primary</WrapperTool>
<Isolated>False</Isolated>
</COMReference>
<COMReference Include="Microsoft.Office.Interop.Excel">
<Guid>{00020813-0000-0000-C000-000000000046}</Guid>
<VersionMajor>1</VersionMajor>
<VersionMinor>6</VersionMinor>
<Lcid>0</Lcid>
<WrapperTool>primary</WrapperTool>
<Isolated>False</Isolated>
</COMReference>
</ItemGroup>
违规者是这个 .Net Interop 参考(需要是 COM 参考):
<Reference Include="Microsoft.Office.Interop.Excel, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c, processorArchitecture=MSIL">
<EmbedInteropTypes>True</EmbedInteropTypes>
</Reference>