因此,我的应用程序中有一层将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.
           });


背后的驱动力是艰巨的任务,必须为大型应用程序在代码中手动声明每个属性。

最佳答案

您需要覆盖.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包装模型。

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覆盖模式将其与相同模型的新副本进行比较。归根结底,我只是认为想出一个“将任何模型与任何模型进行比较”的魔术子弹不是一个好主意,也不实用。

关于c# - 断言两个对象相等,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14508216/

10-15 11:47