繁体   English   中英

MS单元测试是否异常?

[英]Exception in MS Unit Test?

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

方法是

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

单元测试

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

我应该在方法中处理Exception还是缺少其他东西?

编辑:

我通过的路径不是找到文件的路径,因此此测试应该通过...即,如果该路径中不存在文件该怎么办。

在单元测试中,似乎正在部署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");
}

通过放置[ExpectedException(typeof(FileNotFoundException),“找不到文件时引发异常”)]属性,您期望该方法将抛出FileNotFoundException,如果未抛出FileNotFoundException的测试将失败。 否则,测试将成功。

我从不真正了解ExpectedException 您应该能够在代码而不是属性中捕获异常。 这是一种更好的做法,它还可以让您在引发问题后进行处理(例如,进行更多的验证)...它还可以使您停止调试器中的代码并检出内容,而无需在论坛中提问。 :)

我会使用Assert.Throws(TestDelegate code);。
请参阅此处的示例

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM