You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何测试.NET Framework 4.7.1中修改入参的私有方法AddProductionRule

针对你在Visual Studio 2017里基于.NET Framework 4.7.1开发的C#类库,要测试私有方法AddProductionRule的需求,这里给你整理几种实用的测试方案,都是日常开发中常用的思路:

测试私有方法AddProductionRule的可行方案

1. 用反射直接调用私有方法

这种方式不需要修改原有代码结构,适合快速验证私有方法的逻辑:

代码示例:

// 假设你的目标类名为GrammarBuilder
var builderType = typeof(GrammarBuilder);
// 获取私有实例方法的MethodInfo
var addRuleMethod = builderType.GetMethod(
    "AddProductionRule",
    BindingFlags.NonPublic | BindingFlags.Instance);

// 创建类实例
var builderInstance = new GrammarBuilder();

// 准备测试参数
string testBnfLine = "S ::= A B | C\nD";
var testProductionRules = new Dictionary<string, string[]>();

// 调用私有方法
addRuleMethod.Invoke(builderInstance, new object[] { testBnfLine, testProductionRules });

// 验证结果:检查传入的Dictionary是否被正确修改
Assert.IsTrue(testProductionRules.ContainsKey("S"));
Assert.AreEqual(3, testProductionRules["S"].Length); // 对应A B、C、D三个规则

如果目标方法是静态私有方法,只需把BindingFlags.Instance替换为BindingFlags.Static即可。

2. 改为内部方法+InternalsVisibleTo特性

如果觉得反射不够优雅,可以调整方法的访问修饰符,让测试项目合法访问:

步骤:

  1. 修改原方法的访问修饰符为internal:
internal void AddProductionRule(string bnfLine, Dictionary<string, string[]> productionRules)
{
    // 原有逻辑代码
}
  1. 在类库项目的Properties/AssemblyInfo.cs中添加特性,授权测试项目访问内部成员:
// 替换为你的测试项目程序集名称,若有强签名需追加公钥
[assembly: InternalsVisibleTo("YourTestProjectAssemblyName")]
  1. 在测试项目中直接调用方法:
var builder = new GrammarBuilder();
var testRules = new Dictionary<string, string[]>();
builder.AddProductionRule("Expr ::= Term | Expr + Term", testRules);

// 验证逻辑
Assert.AreEqual(2, testRules["Expr"].Length);

3. 用MSTest自带的PrivateObject简化调用

如果你使用Visual Studio内置的MSTest框架,可以用PrivateObject类封装反射逻辑,代码更简洁:

示例代码:

var builder = new GrammarBuilder();
var privateBuilder = new PrivateObject(builder);

string testBnf = "Stmt ::= Assign | IfStmt | WhileStmt";
var testDict = new Dictionary<string, string[]>();

// 直接调用私有方法
privateBuilder.Invoke("AddProductionRule", testBnf, testDict);

// 验证结果
Assert.IsTrue(testDict.ContainsKey("Stmt"));
Assert.AreEqual(3, testDict["Stmt"].Length);

额外注意事项

  • 因为该方法会修改传入的Dictionary参数,务必在每个测试用例前初始化全新的Dictionary实例,避免测试用例之间的状态污染。
  • 针对方法中的Regex.Replace逻辑,建议覆盖特殊场景测试:比如包含换行符、多余空格、特殊符号的BNF行,确保正则处理逻辑符合预期。

内容的提问来源于stack exchange,提问作者VansFannel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:45:07