.net 如何在C#中比较复杂对象作为单元测试的结构
我遇到了以下问题: 目前我正在使用TDD重构我的项目。存在一个我无法更改的域 代码示例:.net 如何在C#中比较复杂对象作为单元测试的结构,.net,unit-testing,.net,Unit Testing,我遇到了以下问题: 目前我正在使用TDD重构我的项目。存在一个我无法更改的域 代码示例: public class Product: IEquatable<Product> { public int Id { get; set; } public string Name { get; set; } public bool Equals(Product other) { if (other == null) re
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
{
公共int Id{get;set;}
公共字符串名称{get;set;}
公共布尔等于(产品其他)
{
如果(其他==null)
返回false;
if(Id==other.Id&&Name==other.Name)
返回true;
返回false;
}
}
[测试类]
公共类产品测试
{
[测试方法]
公共void Test1()
{
var product1=新产品{Id=100,Name=“iPhone”};
var product2=新产品{Id=100,Name=“iPhone”};
Assert.IsTrue(product1.Equals(product2));
}
}
我的目标是找到一个快速解决方案,将复杂对象作为结构进行比较,而不是实现IEquatable,因为我无法扩展业务层。我指的是像Automapper这样的东西,但不是地图,而是比较。请给我一些建议
提前感谢。使用和的代码:
公共类产品
{
公共int Id{get;set;}
公共字符串名称{get;set;}
}
公共静态类测试
{
公共静态void Main()
{
var product1=新产品{Id=100,Name=“iPhone”};
var product2=新产品{Id=100,Name=“iPhone”};
bool x=PropertyCompare.Equal(product1,product2);//true
var Delta=PropertyComparer.GetDelta(产品1,产品2);
//^^=空列表
}
}
将第二个名称
更改为“iPhone2”
会给出false
和一个包含单个条目的列表:“Name”
类似的内容?或:
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
}
}