一些实现错误原始解决方案:
new {Activated = true, Enabled = false}
new {Activated = true, Enabled = true, Extra = "I'm not meant to be here!"}
new {Activated = true, Enabled = "true"}
根据复杂性您的IReportingRepository GetReports方法实现可能值得考虑验证匿名类型的属性值和值类型是否如预期的那样,并且只有预期的属性才存在。
var reportingRepostory = new Mock<IReportingRepository>();
reportingRepostory
.Setup(x => x.GetReports<ServiceReport>(IsAnonymousType(new {Activated = true, Enabled = true})))
.Returns(new List<ServiceReport>(){Report1, Report2});
凡IsAnonymousType方法是:
private static object IsAnonymousType(object expected)
{
return Match.Create(
(object actual) =>
{
if (expected == null)
{
if (actual == null)
return true;
else
return false;
}
else if (actual == null)
return false;
var expectedPropertyNames = expected.GetType().GetProperties().Select(x => x.Name);
var expectedPropertyValues = expected.GetType().GetProperties().Select(x => x.GetValue(expected, null));
var actualPropertyNames = actual.GetType().GetProperties().Select(x => x.Name);
var actualPropertyValues = actual.GetType().GetProperties().Select(x => x.GetValue(actual, null));
return expectedPropertyNames.SequenceEqual(actualPropertyNames)
&& expectedPropertyValues.SequenceEqual(actualPropertyValues);
});
}
太谢谢你了。 – 2012-05-01 08:06:54