你好,我正在尝试测试一个代表 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));
}
}
实际上测试效果很好,我什至发现了两个遗漏的设置,但我认为它写得不好。 可能可以使用接口(interface)的 Moq 来检查是否设置了所有属性。
关于第二个测试,不知道怎么做。可能模拟和检查调用次数可以做到这一点。有帮助吗?
谢谢!
最佳答案
为了测试是否所有属性都设置为特定值,我将为此类实现 Equals()
并创建第二个具有已知值的对象并检查是否相等。这在测试状态变化等时也很方便。
如果没有明确的理由,我当然不会测试一个属性是否被多次设置。
关于c# - 如果设置了所有属性,如何进行单元测试。没有重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12414485/