因此,我的应用程序中有一个层将一种类型的对象
映射到另一种类型。将 ViewModel 视为映射的模型类型。 ViewModel
可能具有名称不同或模型中不存在的属性。反之亦然。
我想测试我的映射层,比较分配,但也允许我为不同的属性提供某种排序边缘情况处理。理想情况下,如果未检查 ViewModel 中的所有属性,测试将会失败。
有人知道这样的野兽是否已经存在吗?
public class CustomerViewModel
{
// This is the same as CustomerModel.CustomerName, but the names differ
public string Name { get; set; }
public int ID { get; set; }
}
public class CustomerModel
{
public string CustomerName { get; set; }
public int ID { get; set; }
}
// Would auto test the properties that match automatically. Additionaltest test for non matching. Fails if all properties aren't tested
Assert.CompareObjects(customerViewModelInstance, customerModelInstance)
.AdditionalTest("Name", "CustomerName")
.AdditionalComplexText((viewModel, model) =>
{
// do some sort of a compare of complex objects. Maybe the viewmodel has address fields, address1, address2 while the Model has an Address object with those fields.
});
这背后的驱动力是一项艰巨的任务,即必须在非常大的应用程序的代码中手动断言每个属性。
最佳答案
您需要重写.Equals()
,以便比较属性
,然后使用
Assert.AreEqual 方法(对象、对象)
。请看下面:
Compare equality between two objects in NUnit
您可能希望在模型本身中实现这样的事情。
// useful class
public class MyStuff
{
public int Id { get; set; }
public string Name { get; set; }
public int MyValue { get; set; }
public override int GetHashCode()
{
return Id;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof (MyStuff)) return false;
var other = obj as MyStuff;
return (other.Id == Id
&& other.MyValue == MyValue
&& other.Equals(other.Name, Name));
// use .Equals() here to compare objects; == for Value types
// alternative weak Equals() for value objects:
// return (other.MyValue == MyValue && other.Equals(other.Name, Name) );
}
}
编辑: 回想起来,我认为在 View 模型和模型中具有重复的属性可能是一个不好的模式,并且是您遇到如此多测试问题的部分原因。相反,您应该允许 ViewModel 包装您的模型。
public class CustomerViewModel
{
// This is the same as CustomerModel.CustomerName, but the names differ
public CustomerModel CustomerModel { get; set; }
pubiic CustomerViewModel()
{
CustomerModel = new CustomerModel();
}
}
public class CustomerModel
{
public string CustomerName { get; set; }
public int ID { get; set; }
}
此时,测试它会更容易,因为您拥有了包装的模型,您可以使用 .Equals 覆盖模式将其与同一模型的新副本进行比较。归根结底,我只是认为试图想出“将任何模型与任何模型进行比较”的 Elixir 不是一个好主意,也不实用。
关于c# - 断言 2 个对象相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14508216/