gpt4 book ai didi

c# - Assert.AreEqual 失败但不应该

转载 作者:可可西里 更新时间:2023-11-01 03:13:47 27 4
gpt4 key购买 nike

我有一个我无法解释的非常奇怪的行为。

我有以下类(class):

public class Project
{
public virtual int Id { get; set; }

public virtual string Name { get; set; }
}

还有一个返回 Project 对象的方法:

public Project GetByName(string Name)
{
using (ISession session = NHibernateHelper.OpenSession())
{
Project project = session.CreateCriteria(typeof(Project))
.Add(Restrictions.Eq("Name", Name))
.UniqueResult<Project>();

return project;
}
}

我添加了一个单元测试来测试 GetByName 方法:

[TestMethod]
public void TestGetByName()
{
IProjectsRepository projectRepository = new ProjectsRepository();

var expected = new Project { Id = 1000, Name = "Project1" };
var actual = projectRepository.GetByName(expected.Name);

Assert.AreEqual<Project>(expected, actual);
}

但是当我运行单元测试时,它在比较两个对象的类型时失败并出现以下错误:

Assert.AreEqual failed. Expected:<MyProject.NHibernate.Project>. Actual:<MyProject.NHibernate.Project>.

为什么断言失败了?


不是 Assert.AreEqual仅断言对象的属性?

根据文档:

Assert.AreEqual Method (Object, Object)

Verifies that two specified objects are equal. The assertion fails if the objects are not equal.

Assert.AreSame Method

Verifies that specified object variables refer to the same object.

最佳答案

您需要覆盖 equals 方法来测试是否相等。默认情况下,它将使用引用比较,并且由于您的预期对象和实际对象位于内存中的不同位置,因此它将失败。这是您应该尝试的方法:

public class Project
{
public virtual int Id { get; set; }

public virtual string Name { get; set; }

public override bool Equals(Object obj)
{
if (obj is Project)
{
var that = obj as Project;
return this.Id == that.Id && this.Name == that.Name;
}

return false;
}
}

您还可以查看 guidelines for overriding equals在 MSDN 上。

关于c# - Assert.AreEqual 失败但不应该,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15463023/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com