In writing unit tests for c# functions, there is a good case made for testing properties. In testing those properties, I felt there should be a few goals.
- Provide a wide range of inputs
- Test additional features like PropertyChanged
- Don't write a ton of very repetitive test code
So I came up with this function for a specific class (although it could even be generalized with a templated method for all classes) that essentially gives a property name, a value to set the property to, the expected value to receive out, and a list of PropertyChanged
names that should be fired as a result. This is accomplished by taking advantage of MSTestv2's DataTestMethod
and DataRow
attributes.
Looking for feedback on the quality/durability/usefulness of this code.
[TestMethod()]
[DataTestMethod]
[DataRow("Name", "A normal name", "A normal name", new string[] { "Name" })]
[DataRow("Name", null, null, new string[] { "Name" })]
[DataRow("Name", "", "", new string[] { "Name" })]
[DataRow("Name", "A normal name", "A normal name", new string[] { "Name" })]
[DataRow("Name", "A really very super duper long string to test the overall allowed length", "A really very super duper long string to test the overall allowed length", new string[] { "Name" })]
[DataRow("Address", 0, 0, new string[] { "Address", "AbsAddress"})]
[DataRow("Address", -1, null, new string[] { "Address", "AbsAddress" })]
[DataRow("Address", 300, 300, new string[] { "Address", "AbsAddress" })]
[DataRow("Address", int.MaxValue, int.MaxValue, new string[] { "Address", "AbsAddress" })]
public void ConfigItem_AllProperties_Test(string propName, object set, object expected, string[] propChangedNames)
{
var item = new ConfigItem();
var propsChanged = new Dictionary<string, bool>();
foreach (var s in propChangedNames)
{
propsChanged.Add(s, false);
}
item.PropertyChanged += (sender, args) =>
{
if (propsChanged.ContainsKey(args.PropertyName))
{
propsChanged[args.PropertyName] = true;
}
};
typeof(ConfigItem).GetProperty(propName).SetValue(item, set);
object actual = typeof(ConfigItem).GetProperty(propName).GetValue(item);
Assert.AreEqual(expected, actual);
foreach (var pair in propsChanged)
{
Assert.IsTrue(pair.Value, pair.Key);
}
}