How do you unit test private methods?

前端 未结 30 1947
无人及你
无人及你 2020-11-22 06:44

I\'m building a class library that will have some public & private methods. I want to be able to unit test the private methods (mostly while developing, but also it coul

30条回答
  •  旧巷少年郎
    2020-11-22 07:45

    Here's an example, first the method signature:

    private string[] SplitInternal()
    {
        return Regex.Matches(Format, @"([^/\[\]]|\[[^]]*\])+")
                            .Cast()
                            .Select(m => m.Value)
                            .Where(s => !string.IsNullOrEmpty(s))
                            .ToArray();
    }
    

    Here's the test:

    /// 
    ///A test for SplitInternal
    ///
    [TestMethod()]
    [DeploymentItem("Git XmlLib vs2008.dll")]
    public void SplitInternalTest()
    {
        string path = "pair[path/to/@Key={0}]/Items/Item[Name={1}]/Date";
        object[] values = new object[] { 2, "Martin" };
        XPathString xp = new XPathString(path, values);
    
        PrivateObject param0 = new PrivateObject(xp);
        XPathString_Accessor target = new XPathString_Accessor(param0);
        string[] expected = new string[] {
            "pair[path/to/@Key={0}]",
            "Items",
            "Item[Name={1}]",
            "Date"
        };
        string[] actual;
        actual = target.SplitInternal();
        CollectionAssert.AreEqual(expected, actual);
    }
    

提交回复
热议问题