I have objects that gets initialized by serializing an XML file.
I’m thinking of including the test data in the test project as an embedded resource instead of “hard-coding” the data in the test method itself.
Embedded Hard-coded approach:
[Test]
public void IsMale_CheckIfGenderIsMale_ReturnsTrue()
{
Human human = new Human();
human.Gender = Gender.Male;
Gender expected = Gender.Male;
Assert.IsTrue((human.Gender == expected));
}
XML approach:
[Test]
public void IsMale_CheckIfGenderIsMale_ReturnsTrue()
{
Human human = Human.Initialize("Human_Male.xml");
Gender expected = Gender.Male;
Assert.IsTrue((human.Gender == expected));
}
Which is a better approach?
We often use embedded xml files in our project for testing. Because we want to test the creation of objects using xml.
It is also good practice to separate the creation of objects from the class itself, for example:
The human class would then have a constructor which takes parameters like gender, and can be called from the HumanFactory class. It’s a separation of concerns that will keep the logic of your class separate from the mechanism of building it.
And when you need a human object for a test, you can choose either to create it directly or use the factory and create it from xml.
I would also simplify the HumanFactory class further, by giving it an xml string (or Stream) instead of a filename. This can make it easier to test – because you can just include the xml in your test code and not in a file:
Otherwise your test depends on either: