我通过比较dto&model和模型对象来做断言。就像这样: -
Assert.AreEqual(_oCustomer.FKCustomerId, actual.FKCustomerId);
Assert.AreEqual(_oCustomer.Name,actual.Name);
Assert.AreEqual(_oCustomer.Description,actual.Description);
但是我想要,而不是为每个测试方法中的每个属性做Assertion,我们可以为它设置任何默认/自动功能吗?任何人都可以指导我吗?
答案 0 :(得分:1)
通过覆盖Equals()
来比较模型与DTO,而不污染您的模型和/或命名空间,您只需创建一个执行比较并在每个测试中调用它的方法。现在你仍然可以逐个属性地断言(所以你可以确切地看到哪一个打破了测试),但你只需要在一个地方改变它。
public static class ModelDtoComparer
{
public static void AssertAreEqual(Model model, Dto dto)
{
Assert.AreEqual(model.FKCustomerId, dto.FKCustomerId);
Assert.AreEqual(model.Name, dto.Name);
Assert.AreEqual(model.Description, dto.Description);
// etc.
}
}
评论回复
要对列表执行此操作,其中modelList
应匹配dtoList
item-for-item:
Assert.AreEqual(modelList.Length, dtoList.Length);
for (var i = 0; i < modelList.Length; i++)
{
ModelDtoComparer.AssertAreEqual(modelList[i], dtoList[i]);
}
答案 1 :(得分:1)
您可以使用反射来编写某种比较器。这将比较给定两个对象的Level 1属性(仅限公共属性):
static void AssertAreEqual<T1, T2>(T1 instance1, T2 instance2) {
var properties1 = typeof(T1).GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty);
var properties2 = typeof(T2).GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty);
var properties = from p1 in properties1
join p2 in properties2 on
p1.Name equals p2.Name
select p1.Name;
foreach (var propertyName in properties) {
var value1 = properties1.Where(p => p.Name == propertyName).First().GetGetMethod().Invoke(instance1, null);
var value2 = properties2.Where(p => p.Name == propertyName).First().GetGetMethod().Invoke(instance2, null);
Assert.AreEqual(value1, value2);
}
}
public class PersonDto {
public string LastName { get; set; }
public int FieldFoo { get; set; }
public int Dto { get; set; }
}
public class PersonModel {
public string LastName { get; set; }
public int FieldFoo { get; set; }
public int Model { get; set; }
}
var p1 = new PersonDto { LastName = "Joe" };
var p2 = new PersonModel { LastName = "Joe" };
AssertAreEqual(p1, p2);
答案 2 :(得分:0)
如果需要,您可以使用反射,这是一个通用方法,您可以使用它来比较任何两个对象,无论它们是什么类型:
public void CompareMyObjects(object object1, object object2)
{
var type1Fields = object1.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetProperty);
var type2Fields = object2.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetProperty);
var propsInCommon = type1Fields.Join(type2Fields, t1 => t1.Name, t2 => t2.Name, (t1, t2) => new { frstGetter = t1.GetGetMethod(), scndGetter = t2.GetGetMethod() });
foreach (var prop in propsInCommon)
{
Assert.AreEqual(prop.frstGetter.Invoke(object1, null), prop.scndGetter.Invoke(object2, null));
}
}
您可以按如下方式使用该方法:
CompareMyObjects(actualCustomer, _oCustomer);
CompareMyObjects(actualAccount, _account);
我希望有所帮助。