2012-07-12 66 views
4

在測試我的代碼中的一些向量操作我要檢查一些公差值相等,因爲float值可能不完全匹配。聲稱使用自定義的比較函數

這意味着,我的測試斷言是這樣的:

Assert.That(somevector.EqualWithinTolerance(new Vec3(0f, 1f, 0f)), Is.True); 

取而代之的是:

Assert.That(somevector, Is.EqualTo(new Vec3(0f, 1f, 0f))); 

這意味着,我的例外情況是這樣的:

Expected: True 
But was: False 

相反其中:

Expected: 0 1 0 
But was: 1 0 9,536743E-07 

讓它更難理解錯誤。

如何使用自定義比較函數,仍然可以獲得很好的異常?

回答

12

找到了答案。 NUnit EqualConstraint有一個預期名稱的方法:Using

所以我只是說這個類:

/// <summary> 
    /// Equality comparer with a tolerance equivalent to using the 'EqualWithTolerance' method 
    /// 
    /// Note: since it's pretty much impossible to have working hash codes 
    /// for a "fuzzy" comparer the GetHashCode method throws an exception. 
    /// </summary> 
    public class EqualityComparerWithTolerance : IEqualityComparer<Vec3> 
    { 
     private float tolerance; 

     public EqualityComparerWithTolerance(float tolerance = MathFunctions.Epsilon) 
     { 
      this.tolerance = tolerance; 
     } 

     public bool Equals(Vec3 v1, Vec3 v2) 
     { 
      return v1.EqualWithinTolerance(v2, tolerance); 
     } 

     public int GetHashCode(Vec3 obj) 
     { 
      throw new NotImplementedException(); 
     } 
    } 

我實例化它,並用它這樣的:

Assert.That(somevector, Is.EqualTo(new Vec3(0f, 1f, 0f)).Using(fuzzyVectorComparer)); 

它更打字,但它是值得的。

相關問題