如何使用Assert(或其他Test类?)来验证是否抛出了异常?
在调试模式下运行MSTEST单元测试时,执行会在每个抛出的预期异常中停止.我的测试看起来像这样
[TestMethod()]
[ExpectedException(typeof(ArgumentNullException))]
public void ShouldThrowExceptionWhenPassingNull()
{
object data = null;
target.CheckNull(data);
}
Run Code Online (Sandbox Code Playgroud)
目标方法如下所示:
public void CheckNull(object data)
{
if (ReferenceEquals(null, data))
{
throw new ArgumentNullException("data");
}
} // test run breaks here: ArgumentNullException was unhandled by user code
Run Code Online (Sandbox Code Playgroud) 我为我的项目方法创建了一个单元测试.当找不到文件时,该方法引发异常.我为此编写了一个单元测试,但是在引发异常时我仍然无法通过测试.
方法是
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)
我应该处理方法中的异常还是我错过了其他的东西?
编辑:
我传递的路径不是找到文件的路径,所以这个测试应该通过...即如果文件不存在于该路径中该怎么办.