2010-03-19 10 views
6

NUnit을 처음 접했고이 테스트가 실패한 이유에 대한 탐구를 찾고 있습니까?NUnit, CollectionAssert.AreEquivalent (..., ...), C# 질문

테스트를 실행할 때 다음 예외가 발생합니다.

은 NUnit.Framework.AssertionException는 : < < ....하여 ExampleClass>, < ....하여 ExampleClass>> 에 해당하지만했다 : 예상 < < ....하여 ExampleClass>, < ... .ExampleClass>> 당신은 당신의 ExampleClassEqualsGetHashCode를 구현해야

using NUnit.Framework; 
using System.Collections.ObjectModel; 

public class ExampleClass 
{ 
    public ExampleClass() 
    { 
     Price = 0m; 
    } 

    public string Description { get; set; } 
    public string SKU { get; set; } 
    public decimal Price { get; set; } 
    public int Qty { get; set; } 
} 

[TestFixture] 
public class ExampleClassTests 
{ 
    [Test] 
    public void ExampleTest() 
    { 

     var collection1 = new Collection<ExampleClass> 
       { 
        new ExampleClass 
         {Qty = 1, SKU = "971114FT031M"}, 
        new ExampleClass 
         {Qty = 1, SKU = "971114FT249LV"} 
       }; 

     var collection2 = new Collection<ExampleClass> 
       { 
        new ExampleClass 
         {Qty = 1, SKU = "971114FT031M"}, 
        new ExampleClass 
         {Qty = 1, SKU = "971114FT249LV"} 
       }; 

     CollectionAssert.AreEquivalent(collection1, collection2); 

    } 
} 

답변

10

2 개의 모음이 동일한 지 확인하기 위해 NUnit은 결국 모음 내의 값을 비교해야합니다. 이 경우 값은 ExampleClass이고 class입니다. Equals 및 GetHashCode 무시와 같은 평등 테스트를 구현하지 않으므로 NUnit은 결국 참조 비교를 수행합니다. 필드마다 값이 같더라도 각 컬렉션에 Example의 다른 인스턴스가 포함되어 있으므로이 작업은 실패합니다.

당신하여 ExampleClass

public override bool Equals(object o) { 
    var other = o as ExampleClass; 
    if (other == null) { return false; } 
    return this.Description == other.Description 
    && this.SKU == other.SKU 
    && this.Price == other.Price 
    && this.Qty == other.Qty; 
} 

public override int GetHashCode() { return 1; } 

주에 다음 추가하여이 문제를 해결할 수 : 나는 GetHashCode의 값 하나를 선택이 변경 가능한 유형과 가변 타입에 GetHashCode있는 유일한 진정한 안전한 반환 값이기 때문에 상수입니다. 이것을 Dictionary<TKey,TValue>의 키로 사용하려는 경우 다시 방문해야합니다.

6

. 이것이 없다면, NUnit은 값 평등이 아닌 참조 동일성 검사 ("이 객체들은 똑같이 보입니까?")를 수행합니다.

+2

Equals를 테스트 목적으로 만 구현하면 균등 오염이 발생할 수 있습니다. http://xunitpatterns.com/Test%20Logic%20in%20Production.html#Equality Pollution –

+0

Equals 재정의가 수정되고 예제 테스트가 작동합니다. 그래서 GetHashCode() 메서드를 재정의하는 것이 좋은 습관입니까 아니면 다른 이유로 필요합니까? 감사! –

+1

'GetHashCode' 구현체는 'Equals'와 일치해야합니다 : 두 객체가 같으면 같은 해시 코드를 가져야합니다. 두 객체는 ​​서로 다른 해시 코드를 가질 수 있지만 서로 다른 객체가 동일한 해시 코드를 갖는 경우 'Equals'는 false를 반환해야합니다. –