Assert.AreEqual 失败,而它不应该 [英] Assert.AreEqual fails while it shouldn't

查看:37
本文介绍了Assert.AreEqual 失败,而它不应该的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a really weird behavior which I cannot explain.

我有以下课程:

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

    public virtual string Name { get; set; }
}

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

And a method which returns a Project object:

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 方法:

I have added a Unit Test to test the GetByName method:

[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);
}

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

But when I run the unit test it fails when comparing the type of the two objects with the following error:

Assert.AreEqual 失败.预期:.实际:.

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

为什么断言失败?

不是 Assert.AreEqual 仅对对象?

根据文档:

Assert.AreEqual 方法(对象,对象)

验证两个指定的对象是否相等.断言失败,如果对象不相等.

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

Assert.AreSame 方法

验证指定的对象变量是否引用同一个对象.

Verifies that specified object variables refer to the same object.

推荐答案

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

You need to override the equals method to test for equality. By default it will use reference comparison, and since your expected and actual objects are in different locations in memory it will fail. Here is what you should try:

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

您还可以查看 MSDN 上的覆盖等号的指南.

You can also check out the guidelines for overriding equals on MSDN.

这篇关于Assert.AreEqual 失败,而它不应该的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆