MS单元测试中的例外情况?

Paw*_*anS 4 c# unit-testing expected-exception

我为我的项目方法创建了一个单元测试.当找不到文件时,该方法引发异常.我为此编写了一个单元测试,但是在引发异常时我仍然无法通过测试.

方法是

public string[] GetBuildMachineNames(string path)
{
    string[] machineNames = null;

    XDocument doc = XDocument.Load(path);

    foreach (XElement child in doc.Root.Elements("buildMachines"))
    {
        int i = 0;
        XAttribute attribute = child.Attribute("machine");
        machineNames[i] = attribute.Value;
    }
    return machineNames;
}
Run Code Online (Sandbox Code Playgroud)

单元测试

[TestMethod]
[DeploymentItem("TestData\\BuildMachineNoNames.xml")]
[ExpectedException(typeof(FileNotFoundException),"Raise exception when file not found")]
public void VerifyBuildMachineNamesIfFileNotPresent()
{
    var configReaderNoFile = new ConfigReader();
    var names = configReaderNoFile.GetBuildMachineNames("BuildMachineNoNames.xml");
}
Run Code Online (Sandbox Code Playgroud)

我应该处理方法中的异常还是我错过了其他的东西?

编辑:

我传递的路径不是找到文件的路径,所以这个测试应该通过...即如果文件不存在于该路径中该怎么办.

Dar*_*rov 6

在您的单元测试中,您似乎正在部署一个xml文件:TestData\BuildMachineNoNames.xml您要传递给它GetBuildMachineNames.所以文件存在,你不能指望FileNotFoundException抛出.所以也许是这样的:

[TestMethod]
[ExpectedException(typeof(FileNotFoundException), "Raise exception when file not found")]
public void VerifyBuildMachineNamesIfFileNotPresent()
{
    var configReaderNoFile = new ConfigReader();
    var names = configReaderNoFile.GetBuildMachineNames("unexistent.xml");
}
Run Code Online (Sandbox Code Playgroud)