我正在尝试使用测试驱动设计方法编写应用程序 - 我对单元测试还很新,所以我想知道正确的测试正确输入和异常的方法。
我有一个用于加载配置文件的类:
class Config
{
private XmlDocument configfile;
public Config()
{
configfile = new XmlDocument();
}
public void LoadConfigFile(string filename)
{
if(string.IsNullOrEmpty(filename))
throw new System.ArgumentException("You must specify a filename");
try
{
configfile.Load(filename);
}
catch (Exception ex)
{
throw new System.IO.FileNotFoundException("File could not be loaded");
}
}
}
因此,这里可以进行三个测试:
- 加载实际文件并确保没有错误
- 尝试加载无效文件(不存在的文件)
- 不指定文件名参数
正确的测试方法是编写3个测试方法,像这样吗?
/// <summary>
///A test for LoadConfigFile
///</summary>
[TestMethod()]
public void LoadConfigFileTest()
{
Config target = new Config(); // TODO: Initialize to an appropriate value
string filename = "config.xml"; // TODO: Initialize to an appropriate value
target.LoadConfigFile(filename);
Assert.Inconclusive("A method that does not return a value cannot be verified.");
}
/// <summary>
///A test for LoadConfigFile
///</summary>
[TestMethod()]
[ExpectedException(typeof(System.ArgumentException))]
public void LoadConfigFileTest1()
{
Config target = new Config(); // TODO: Initialize to an appropriate value
string filename = ""; // TODO: Initialize to an appropriate value
target.LoadConfigFile(filename);
Assert.Inconclusive("A method that does not return a value cannot be verified.");
}
/// <summary>
///A test for LoadConfigFile
///</summary>
[TestMethod()]
[ExpectedException(typeof(System.IO.FileNotFoundException))]
public void LoadConfigFileTest2()
{
Config target = new Config(); // TODO: Initialize to an appropriate value
string filename = "blah.xml"; // TODO: Initialize to an appropriate value
target.LoadConfigFile(filename);
Assert.Inconclusive("A method that does not return a value cannot be verified.");
}
此外,这3个测试中是否都应该加上try {} catch () {}语句? 就像第一个测试一样,正确性是暗示的,在第二个和第三个测试中,我无论如何都要检查异常,因此异常对测试没有影响。