VansFannel
VansFannel

Reputation: 45921

PrivateObject get argument modified inside a method

I'm developing a C# library with .NET Framework 4.7.1 and Visual Studio 2017.

I want to test this method:

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);
}

With this Nunit method:

[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);
}

But it fails because actualRules remains as null and I don't know how to get the value of productionRules dictionary from a PrivateObject (Nuget <package id="Microsoft.VisualStudio.QualityTools.UnitTestFramework.Updated" version="15.0.26228" targetFramework="net471" />).

If I add out to the parameter, I get an error here: if (productionRules == null). I think the method should work because productionRules is a reference.

I've thought to return the Key, Value pair from the method but I don't know how to declare it.

How can I test this method with PrivateObject?

Upvotes: 1

Views: 339

Answers (0)

Related Questions