본문 바로가기

Web_Application/ASP.NET MVC UnitTest

C# Override Object Equals



/***
 * Excerpted from "Test Drive ASP.NET MVC",
 * published by The Pragmatic Bookshelf.
 * Copyrights apply to this code. It may not be used to create training material, 
 * courses, books, articles, and the like. Contact us if you are in doubt.
 * We make no guarantees that this code is fit for any purpose. 
 * Visit http://www.pragmaticprogrammer.com/titles/jmasp for more book information.
***/
using System;
using System.Collections.Generic;
using System.Drawing;

namespace WebApplication1.Models
{
    public class Topic
    {
        public static List<Topic> Topics = new List<Topic>
        {
            new Topic {Id = 1, Color = Color.Red, Name = "Work"},
            new Topic {Id = 2, Color = Color.Blue, Name = "Home"}
        };

        public int Id { get; set; }
        public Color Color { get; set; }
        public string Name { get; set; }

        public string ColorInWebHex()
        {
            return ColorTranslator.ToHtml(Color);
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            if (obj.GetType() != typeof (Topic)) return false;
            var other = (Topic) obj;
            return other.Id == Id && 
                other.Color.Equals(Color) && 
                Equals(other.Name, Name); ;
        }

        public override int GetHashCode()
        {
            unchecked
            {
                int result = Id;
                result = (result*397) ^ Color.GetHashCode();
                result = (result*397) ^ (Name != null ? Name.GetHashCode() : 0);
                return result;
            }
        }
    }
}



p63

두 객체의 동일성 여부를 파악할 수 있는 관점들

널 검사 : 비교 하려는 객체가 초기화되어 있는가?

참조 검사 : 비교하려는 객체가 동일한 메모리 공간에 존재하는가?

타입 검사 : 비교하려는 객체가 동일한 클래스의 인스턴스인가?

값 검사 : 모든 속성과 필드의 값이 일치하는가?


출처 : Test-Drive ASP.NET MVC - 테스트 주도 ASP.NET MVC 프로그래밍


'Web_Application > ASP.NET MVC UnitTest' 카테고리의 다른 글

[NSubstitute] HttpContext Mock  (0) 2017.01.12