Hello I’m trying to test a class that represents layout theme of GUI. It has color and size properties and a method that sets the default values.
public class LayoutTheme : ILayoutTheme
{
public LayoutTheme()
{
SetTheme();
}
public void SetTheme()
{
WorkspaceGap = 4;
SplitBarWidth = 4;
ApplicationBack = ColorTranslator.FromHtml("#EFEFF2");
SplitBarBack = ColorTranslator.FromHtml("#CCCEDB");
PanelBack = ColorTranslator.FromHtml("#FFFFFF ");
PanelFore = ColorTranslator.FromHtml("#1E1E1E ");
// ...
}
public int WorkspaceGap { get; set; }
public int SplitBarWidth{ get; set; }
public Color ApplicationBack { get; set; }
public Color SplitBarBack { get; set; }
public Color PanelBack { get; set; }
public Color PanelFore { get; set; }
// ...
}
I need to test:
1. If all of the properties are set by the SetTheme method.
2. If there is no duplication in setting a property.
For the first test, I first cycle through all properties and set an unusual value. After that I call SetTheme method and cycle again to check if all properties are changed.
[Test]
public void LayoutTheme_IfPropertiesSet()
{
var theme = new LayoutTheme();
Type typeTheme = theme.GetType();
PropertyInfo[] propInfoList = typeTheme.GetProperties();
int intValue = int.MinValue;
Color colorValue = Color.Pink;
// Set unusual value
foreach (PropertyInfo propInfo in propInfoList)
{
if (propInfo.PropertyType == typeof(int))
propInfo.SetValue(theme, intValue, null);
else if (propInfo.PropertyType == typeof(Color))
propInfo.SetValue(theme, colorValue, null);
else
Assert.Fail("Property '{0}' of type '{1}' is not tested!", propInfo.Name, propInfo.PropertyType);
}
theme.SetTheme();
// Check if value changed
foreach (PropertyInfo propInfo in propInfoList)
{
if (propInfo.PropertyType == typeof(int))
Assert.AreNotEqual(propInfo.GetValue(theme, null), intValue, string.Format("Property '{0}' is not set!", propInfo.Name));
else if (propInfo.PropertyType == typeof(Color))
Assert.AreNotEqual(propInfo.GetValue(theme, null), colorValue, string.Format("Property '{0}' is not set!", propInfo.Name));
}
}
Actually the test works well and I even found two missed settings, but I don’t think it is written well.
Probably it can be don with Moq of the interface and check if all properties are set.
About the second test, don’t have idea how to do it. Probably mocking and checking the number of calls can do it. Any help?
Thank you!
For testing if all properties are set to certain values, I would implement
Equals()for this class and create a second object with known values and check for equality. This also comes in handy when testing for state changes etc.I would certainly not test if a property gets set multiply times if there is no explicit reason to do it.