所以,我的应用程序中有一个图层将一种类型的object
映射到另一种类型。考虑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.
});
这背后的驱动力是必须在代码中手动断言每个属性的艰巨任务。
答案 0 :(得分:2)
您需要覆盖.Equals()
,以便与properties
进行比较,然后使用
Assert.AreEqual Method (Object, Object)
。请参阅以下内容:
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) );
}
}
修改强> 回想起来,我已经决定在viewmodel和model中复制属性可能是一个糟糕的模式,这也是你遇到很多测试问题的部分原因。相反,您应该允许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覆盖模式与同一模型的新副本进行比较。在一天结束时,我只是不认为尝试提出一个“将任何模型与任何模型进行比较”的灵丹妙药是一个好主意,也不实用。