如何在单元测试中比较两个对象?

编程入门 行业动态 更新时间:2024-10-27 08:37:34
本文介绍了如何在单元测试中比较两个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 public class Student { public string Name { get; set; } public int ID { get; set; } }

...

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.

更多推荐

如何在单元测试中比较两个对象?

本文发布于:2023-11-03 19:56:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1555944.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:单元   对象   两个   如何在   测试中

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!