测试未公开类及方法
测试未公开类方法 I
# 在待测试项目代码文件中加入, IoxMcpServer.Test 为测试项目
using System.Runtime.CompilerServices;
[assembly:InternalsVisibleTo("IoxMcpServer.Test")]
测试未公开类方法 II
# 在待测试项目文件中加入, IoxMcpServer.Test 为测试项目
<ItemGroup>
<InternalsVisibleTo Include="IoxMcpServer.Test"/>
</ItemGroup>
测试类私有方法
- 可以使用反射的方式调用
- .net framework 可以使用
PrivateObject
- nuget 上有三方实现的
PrivateObject
比如Unofficial.Microsoft.VisualStudio.QualityTools.UnitTestFramework
private
方法可能会被编译器优化
[DynamicDependency(DynamicallyAccessedMemberTypes.All, typeof(CityWeatherTools))]
private string Test(DateTime time) { return $"{Guid.NewGuid().GetHashCode()} # {time}"; }
调用
var privateObject = new PrivateObject(service);
var result = privateObject.Invoke("Test", DateTime.Now);
下面的经验有空再整理
http://www.liangzhou.pro/posts/csharp_how_to_test_a_private_method/