As another example I have a CityFactory class, which returns
an array of City objects. However, the business class will default to the
NullCity implementation if no value has been provided yet. So, the City
definition has properties of ID and Name.
Listing 5
public class City
{
private int _id;
private string _name;
public int ID
{
get
{
return _id;
}
}
public string Name
{
get
{
return _name;
}
}
}
The NullCity defaults the ID to -1 and the Name to empty
through the NullCity constructor (using the technique for nullable objects
above, not because of the default values of City). The following is a NUnit
test that shows the flow in the application, as city defaults to a null value,
and then gets populated from the factory later.
Listing 6
[Test]
public void TestCity()
{
City city = NullCity.Empty();
Assert.AreEqual( - 1, city.ID);
Assert.AreEqual(string.Empty, city.Name);
city = CityFactory.GetCities()[0];
Assert.AreEqual(1, city.ID);
Assert.AreEqual("Pittsburgh", city.Name);
}
The test runs successfully. The code is available with a
unit test to illustrate the process and it can be downloaded from the URL given
in the download section.