[英]C# ValidationResult value equality assertion fails with Assert.AreEqual
我有一个简单的ValidationRule实现:
public class IntegerRangeRule : ValidationRule
{
public Int32 Max { get; set; }
public Int32 Min { get; set; }
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
int integer;
if(string.IsNullOrEmpty((string)value))
{
return new ValidationResult(false, "Field cannot be empty");
}
if (Int32.TryParse((string) value, out integer))
{
if((integer < Min) || (integer > Max))
return new ValidationResult(false, string.Format("Enter a value between {0} and {1}.", Min, Max));
}
else
{
return new ValidationResult(false, "Illegal characters: " + (string)value);
}
return ValidationResult.ValidResult;
}
}
我为Validation
方法编写了以下单元测试:
[TestMethod()]
public void ValidateTest_InputTooSmall()
{
//Setup
var target = new IntegerRangeRule()
{
Max = 100,
Min = 1
};
var expected = new ValidationResult(false, "Enter a value between 1 and 100.");
//Exercise
var actual = target.Validate("0", null);
//Verify
Assert.AreEqual(expected.ErrorContent, actual.ErrorContent);
Assert.AreEqual(expected.IsValid, actual.IsValid);
Assert.AreEqual(expected.GetHashCode(), actual.GetHashCode());
Assert.AreEqual(expected, actual);
}
这里是要抓住的地方。
前三个断言全部通过。 但是最后一个失败了。
如果我更换
...
if (Int32.TryParse((string) value, out integer))
{
if((integer < Min) || (integer > Max))
return new ValidationResult(false, string.Format("Enter a value between {0} and {1}.", Min, Max));
}
...
用一个恒定的字符串。
...
if (Int32.TryParse((string) value, out integer))
{
if((integer < Min) || (integer > Max))
return new ValidationResult(false, "Enter a value between 1 and 100.");
}
...
最后一个断言将通过。
我不明白是什么引起了这里的问题。 谢谢。
ValidationResult在Equals中包含以下内容:
return (IsValid == vr.IsValid) && (ErrorContent == vr.ErrorContent);
由于ErrorContent
是对象,因此这是引用比较,而不是值比较。 在您的情况下,您正在使用String.Format
生成一个新字符串,并将该引用与文字进行比较,因此结果始终为false。 当您将其更改为相同的文字字符串时,它会通过,因为文字是由CLR插入的。
同时,您的测试框架可能在其Assert.AreEqual
方法内调用Object.Equals(object, object)
,该方法调用String的重写Equals方法。 进行值比较。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.