单元测试默认断言方法

本文关键字:方法 断言 默认 单元测试 | 更新日期: 2023-09-27 17:53:53

我通过比较dto和模型对象来做断言。像这样:-

Assert.AreEqual(_oCustomer.FKCustomerId, actual.FKCustomerId);
Assert.AreEqual(_oCustomer.Name,actual.Name);
Assert.AreEqual(_oCustomer.Description,actual.Description); 

但我想,而不是做断言在每个测试方法的每个属性,我们可以有任何默认/自动功能吗?有人能指点我一下吗?

单元测试默认断言方法

您可以使用反射来编写某种比较器。这将比较给定两个对象的Level1属性(仅限公共属性):

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);

通过覆盖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]);
}

如果你愿意,你可以使用反射,这里有一个通用方法,你可以用它来比较任何两个对象,不管它们是什么类型的:

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);