如何在 C# 测试与生产环境中切换 Class 的访问级别
结论
一般不用在 public 和 internal 之间切换。类型可以一直保持 internal,并通过 InternalsVisibleTo 向测试程序集开放访问。这样,测试代码和生产代码使用同一份实现,也不会把测试专用类型暴露为公共 API。
使用 InternalsVisibleTo
假设测试程序集名为 MyProduct.Tests,可以在生产项目中添加 AssemblyInfo.cs 文件:
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("MyProduct.Tests")]
接口继续声明为 internal:
using System;
internal interface ILdapService : IDisposable
{
/// <summary>
/// Verifies the LDAP credentials.
/// </summary>
/// <param name="email">LDAP user name without domain name.</param>
/// <param name="password">LDAP password.</param>
bool Verify(string email, string password);
}
测试项目便可以直接使用该接口:
[TestClass]
public class LdapServiceTests
{
[TestMethod]
public void Verify_WithInvalidCredentials_ReturnsFalse()
{
ILdapService service = CreateService();
bool result = service.Verify("user", "invalid-password");
Assert.IsFalse(result);
}
private static ILdapService CreateService()
{
// 根据实际构造方式创建实例
throw new NotImplementedException();
}
}
InternalsVisibleTo 中需要填写测试程序集名称,这个名称不一定与项目文件名相同。可以在测试项目的 .csproj 中查看 <AssemblyName>。如果没有显式配置,通常会使用项目名称。
有多个测试程序集时,需要逐一声明:
[assembly: InternalsVisibleTo("MyProduct.UnitTests")]
[assembly: InternalsVisibleTo("MyProduct.IntegrationTests")]
在项目文件中配置
SDK 风格的项目也可以直接在生产项目的 .csproj 中生成该程序集特性:
<ItemGroup>
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleToAttribute">
<_Parameter1>MyProduct.Tests</_Parameter1>
</AssemblyAttribute>
</ItemGroup>
这种配置与在 AssemblyInfo.cs 中添加 InternalsVisibleTo 的作用相同,任选一种即可。
生成两种不同的程序集
如果明确要求接口在测试构建中为 public、在生产构建中为 internal,可以使用条件编译:
#if TEST_BUILD
public interface ILdapService : IDisposable
#else
internal interface ILdapService : IDisposable
#endif
{
bool Verify(string email, string password);
}
然后在测试构建配置中定义 TEST_BUILD。
SDK 风格的 .csproj 可以这样配置:
<PropertyGroup Condition="'$(Configuration)' == 'Test'">
<DefineConstants>$(DefineConstants);TEST_BUILD</DefineConstants>
</PropertyGroup>
构建时指定相应配置:
dotnet build --configuration Test
在 Visual Studio 中,也可以通过项目属性的“生成”页面,为指定配置添加条件编译符号。
注意事项
条件编译会生成两个公共 API 不同的程序集。测试针对的是测试版本,实际发布的则是另一个版本,因此可能漏掉生产构建中的编译错误或行为差异。采用这种方式时,还应单独构建并验证生产配置。
InternalsVisibleTo 不会把类型改为 public,它只是将指定程序集声明为友元程序集,通常更适合单元测试。
如果程序集使用强名称签名,InternalsVisibleTo 中需要填写测试程序集的完整公钥,而非 public key token:
[assembly: InternalsVisibleTo(
"MyProduct.Tests, PublicKey=<完整公钥>"
)]
internal 也不是安全边界。它用于限制正常的编译期访问,不能保护密码、密钥或其他敏感数据。
备注:内容仅供参考。
