我正在使用.NET Framework 4.7.1和Visual Studio 2017开发一个C#库。
我想测试一下这个方法:
private void AddProductionRule(
string bnfLine,
Dictionary<string, string[]> productionRules)
{
if (productionRules == null)
productionRules = new Dictionary<string, string[]>();
string[] stringSplitted = bnfLine.Split(new[] { "::=" }, StringSplitOptions.None);
string key = stringSplitted[0].Trim();
string[] rules;
stringSplitted[1] = Regex.Replace(stringSplitted[1], "[::=\r\n]", string.Empty).Trim();
rules = stringSplitted[1].Split('|').Select(rule => rule.Trim()).ToArray();
productionRules.Add(key, rules);
}
使用这种Nunit方法:
[Test]
public void ShouldAddProductionRule()
{
// Arrange
PrivateObject privateObject = new PrivateObject(grammar);
string line = "<expr> ::= <expr><op><expr>\r\n| (<expr><op><expr>)\r\n| <pre_op>(<expr>)\r\n| <var>";
Dictionary<string, string[]> expectedRules = new Dictionary<string, string[]>
{
{ "<expr>", new string[] { "<expr><op><expr>", "(<expr><op><expr>)", "<pre_op>(<expr>)", "<var>" } }
};
Dictionary<string, string[]> actualRules = null;
object[] args = new object[2] { line, actualRules };
// Act
privateObject.Invoke("AddProductionRule", args);
actualRules = args[1] as Dictionary<string, string[]>;
// Assert
NUnit.Framework.CollectionAssert.AreEqual(expectedRules, actualRules);
}
但它失败了,因为actualRules
仍为空,我不知道如何从productionRules
(Nuget PrivateObject
)获取<package id="Microsoft.VisualStudio.QualityTools.UnitTestFramework.Updated" version="15.0.26228" targetFramework="net471" />
字典的值。< / p>
如果我在参数中添加out
,我会在此处收到错误:if (productionRules == null)
。我认为该方法应该有效,因为productionRules
是一个参考。
我曾想过从方法中返回Key, Value
对,但我不知道如何声明它。
如何使用PrivateObject
测试此方法?