Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a really weird behavior which I cannot explain.

I have the following class:

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

    public virtual string Name { get; set; }
}

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

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 failed. Expected:<MyProject.NHibernate.Project>. Actual:<MyProject.NHibernate.Project>.

Why is the assertion failing?


Isn't Assert.AreEqual asserting only on the properties of the objects?

According to the documentation:

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
633 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...