单元测试void方法

bin*_*nks 1 c# unit-testing

我知道您可以通过检查其效果来单元测试void方法.但是,查看此代码中的loadConfigFile方法:

    internal XmlDocument configData;

    public ConfigFile()
    {
        configData = new XmlDocument();
    }

    /// <summary>
    /// Load config file into memory
    /// </summary>
    /// <param name="filename">path and filename of config file</param>
    public void loadConfigFile(string filename) 
    {
        if(string.IsNullOrEmpty(filename))
            throw new System.ArgumentException("You must specify a filename");

        try 
        {
            configData.Load(filename);
        }
        catch(Exception ex)
        {
            throw new Exception("Config file could not be loaded",ex);
        }
    }
Run Code Online (Sandbox Code Playgroud)

它将配置文件加载到私有字段中 - 需要将其保密,以便开发人员不直接修改该值.相反,修改将通过setConfigValue和getConfigValue方法完成(我假设需要单独测试).

鉴于此,我如何测试loadConfigFile实际工作?因为我无法访问私有configData字段.

Jas*_*ans 6

configData使用该课程的其他地方?

比方说,如果你有一个类似的方法

public string GetValue()
{
    return configData.GetsomeDataFromThis;
}
Run Code Online (Sandbox Code Playgroud)

然后我建议你进行这样的测试:

public void ReadValueFromLoadedConfigData()
{
    // Arrange.
    const string ExpectedValue = "Whatever";

    var sut = new ConfigFile();

    sut.loadConfigFile(@"C:\PathToTheConfigFile");

    // Act.
    string actual = sut.GetConfigValue();

    // Assert.
    Assert.AreEqual(ExpectedValue, actual);
}
Run Code Online (Sandbox Code Playgroud)

在您的测试中,尝试仅测试公共交互,因为通过必须读取私有字段的值深入到类中,意味着您的类不是测试友好的.