I'm trying to write an application using the Test Driven Design approach - I'm quite new to unit tests, so I'm just wondering what the right way to test for correct inputs and exceptions is.
I have this class that's used to load a config file:
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");
}
}
}
So, there are 3 tests that can be performed here:
- load an actual file and make sure there are no errors
- try to load an invalid file (one that doesnt exist)
- do not specify an filename argument
Is the correct way to test these, to write 3 test methods, like so?:
/// <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.");
}
Also, should all 3 of these tests have try {} catch () {} statements? As in the first test, the correctness is implied, and in the 2nd and 3rd tests, I'm checking for an exception anyway, so an exception is of no consequence to the tests.