【问题标题】:How to compare complex objects as structures in C# for Unit Tests如何在 C# 中将复杂对象作为结构进行比较以进行单元测试
【发布时间】:2011-09-10 17:04:07
【问题描述】:

我遇到了以下问题: 目前我正在使用 TDD 重构我的项目。有一个我无法更改的现有域。

代码示例:

public class Product: IEquatable<Product>
{
    public int Id { get; set; }
    public string Name { get; set; }

    public bool Equals(Product other)
    {
        if (other == null)
            return false;
        if (Id == other.Id && Name == other.Name)
            return true;
        return false;
    }
}


[TestClass]
public class ProductTest
{
    [TestMethod]
    public void Test1()
    {
        var product1 = new Product {Id = 100, Name = "iPhone"};
        var product2 = new Product {Id = 100, Name = "iPhone"};
        Assert.IsTrue(product1.Equals(product2));
    }
}

我的目标是找到一个快速的解决方案,将复杂对象作为结构进行比较,而不是实现 IEquatable,因为我无法扩展业务层。我的意思是 Automapper 之类的东西,但不是为了映射,而是为了比较。请给点建议。

提前致谢。

【问题讨论】:

标签: .net unit-testing


【解决方案1】:

使用来自herehere 的代码:

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
}


public static class ProductTest
{
    public static void Main()
    {
        var product1 = new Product { Id = 100, Name = "iPhone" };
        var product2 = new Product { Id = 100, Name = "iPhone" };
        bool x = PropertyCompare.Equal(product1, product2); // true

        var deltas = PropertyComparer<Product>.GetDeltas(product1, product2);
        // ^^= an empty list
    }
}

将第二个Name 更改为"iPhone2" 会得到false 和一个包含单个条目的列表:"Name"

【讨论】:

    猜你喜欢
    • 2021-12-07
    • 1970-01-01
    • 2020-08-10
    • 2012-06-03
    • 1970-01-01
    • 2019-07-30
    • 1970-01-01
    • 2016-09-26
    • 1970-01-01
    相关资源
    最近更新 更多