...
var st1 = new Student { ID = 20, Name = "ligaoren", }; var st2 = new Student { ID = 20, Name = "ligaoren", }; Assert.AreEqual<Student>(st1, st2);// How to Compare two object in Unit test?如何比较Unitest中的两个集合?
How to Compare two collection in Unitest?
推荐答案您正在寻找的是 xUnit测试模式被称为测试专用的平等。
What you are looking for is what in xUnit Test Patterns is called Test-Specific Equality.
尽管有时您可以选择覆盖Equals方法,但这可能会导致平等污染,因为您需要测试的实现对于一般类型而言可能不是正确的。
While you can sometimes choose to override the Equals method, this may lead to Equality Pollution because the implementation you need to the test may not be the correct one for the type in general.
例如,域驱动设计区分实体和值对象,以及那些
For example, Domain-Driven Design distinguishes between Entities and Value Objects, and those have vastly different equality semantics.
在这种情况下,您可以为相关类型编写自定义比较。
When this is the case, you can write a custom comparison for the type in question.
如果您厌倦了这样做,请 AutoFixture 的Likeness类提供通用的特定于测试的平等性。对于学生类,这将允许您编写如下测试:
If you get tired doing this, AutoFixture's Likeness class offers general-purpose Test-Specific Equality. With your Student class, this would allow you to write a test like this:
[TestMethod] public void VerifyThatStudentAreEqual() { Student st1 = new Student(); st1.ID = 20; st1.Name = "ligaoren"; Student st2 = new Student(); st2.ID = 20; st2.Name = "ligaoren"; var expectedStudent = new Likeness<Student, Student>(st1); Assert.AreEqual(expectedStudent, st2); }这不需要您覆盖学生平等。
This doesn't require you to override Equals on Student.
Likeness执行语义比较,因此它也可以比较两种不同的类型,只要它们在语义上相似。
Likeness performs a semantic comparison, so it can also compare two different types as long as they are semantically similar.
更多推荐
如何在单元测试中比较两个对象?
发布评论