开发者

How to compare complex objects as structures in C# for Unit Tests

开发者 https://www.devze.com 2023-03-11 00:29 出处:网络
I came across the following problem: Currently I\'m refactoring my project using TDD. There is an existed domain that I can\'t change.

I came across the following problem: Currently I'm refactoring my project using TDD. There is an existed domain that I can't change.

Code example:

public class Product: IEquatable<Product开发者_StackOverflow社区>
{
    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));
    }
}

My goal is to find a quick solution to compare complex objects as structures and not implement IEquatable cause I can't extend bussiness layer. I mean something like Automapper but not to map but just to compare. Please, give some advices.

Thank in advance.


Using the code from here and here:

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
    }
}

changing the second Name to "iPhone2" gives false and a list containing the single entry: "Name".

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号