2

所以,我的应用程序中有一个层可以将一种类型的 a 映射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.
           });

这背后的驱动力是一项艰巨的任务,即必须在非常大的应用程序的代码中手动声明每个属性。

4

1 回答 1

2

您需要覆盖.Equals()以便进行比较properties,然后使用

Assert.AreEqual Method (Object, Object). 请看下面:

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

于 2013-01-24T18:32:29.870 回答