您好我正在尝试测试一个代表GUI布局主题的类。它具有颜色和大小属性以及设置默认值的方法。
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; }
// ...
}
我需要测试: 1.如果所有属性都由SetTheme方法设置。 2.如果设置属性没有重复。
对于第一个测试,我首先遍历所有属性并设置一个异常值。之后我调用SetTheme方法并再次循环以检查是否所有属性都已更改。
[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));
}
}
实际上测试效果很好,我甚至发现了两个错过的设置,但我认为它写得不好。 可能它可能是接口的Moq并检查是否所有属性都已设置。
关于第二次测试,不知道该怎么做。可能模拟和检查呼叫的数量可以做到这一点。有什么帮助吗?
谢谢!
答案 0 :(得分:0)
为了测试是否所有属性都设置为特定值,我将为此类实现Equals()
并创建具有已知值的第二个对象并检查是否相等。在测试状态变化等时,这也很方便。
如果没有明确的理由,我肯定不会测试属性是否设置了倍数。