Assert.AreEqual fails while it shouldn't

前端 未结 4 1376
小鲜肉
小鲜肉 2020-12-09 04:33

I have a really weird behavior which I cannot explain.

I have the following class:

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

           


        
4条回答
  •  一个人的身影
    2020-12-09 05:36

    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.

提交回复
热议问题