.net - 考虑到开发人员的时间对 GetHashCode 进行单元测试

标签 .net unit-testing iequalitycomparer

在我当前的项目中,我有几个 IEqualitycomparers。
这些获取对象的几个属性并进行比较。
属性可以是相等的,也可以是不同的,这对于值和 null 都是如此。

我想对这些进行单元测试,但所有不同的可能性都是疯狂的。
我怎样才能有效地测试这些?

更新
目前,它们通过属性而不是构造函数获取它们的值,因为它们充满了 entlib 的数据块。

示例(在 vb.net 中,但我也谈论 C#):

Public Class GuarantyEqualityComparer
    Implements IEqualityComparer(Of Guaranty)

    Public Overloads Function Equals(x As Guaranty, y As Guaranty) As Boolean Implements IEqualityComparer(Of Guaranty).Equals
        Return x.ClientCode = y.ClientCode AndAlso x.LocationCode = y.LocationCode AndAlso x.CategoryCode = y.CategoryCode AndAlso x.GuarantyCode = y.GuarantyCode
    End Function

    Public Overloads Function GetHashCode(obj As Guaranty) As Integer Implements IEqualityComparer(Of Guaranty).GetHashCode
        Const format As String = "{0}{1}{2}{3}"
        Return String.Format(CultureInfo.InvariantCulture, format, obj.ClientCode, obj.LocationCode, obj.CategoryCode, obj.GuarantyCode).GetHashCode()
    End Function
End Class

最佳答案

好的,考虑到有一个构造函数的可能性,我会尝试编写一个实用程序类,它允许您为每个构造函数参数指定示例值:

var comparer = new GuarantyEqualityComparer();
var tester = EqualityTester<Guaranty>.CreateBuilder(comparer)
                 .AddValue("ClientCode", "Sample1", "Sample2", null)
                 .AddValue("LocationCode", 1, 3, 0)
                 .Builder();
tester.Test();

测试人员会检查每个可能的排列,并至少检查:
  • x.Equals(y)xy使用相同的值构建
  • x.GetHashCode() == y.GetHashCode()xy使用相同的值构建
  • !x.Equals(y)xy用不同的值构建

  • 它还可以检查 x.GetHashCode() != y.GetHashCode()xy是用不同的值(value)观 build 的。这不是GetHashCode的契约(Contract)所要求的。 ,即使是一个好的哈希码也总会有失败的情况(对于具有超过 232 个可能值的任何类型),但它仍然是一个合理的健全性检查 - 您通常必须非常不幸地选择样本值代码正确时失败。

    在哈希码生成方面,我总是使用以下内容:
    int hash = 19;
    hash = hash * 31 + HashOfField1;
    hash = hash * 31 + HashOfField2;
    ...
    return hash;
    

    对于野田时间,我们在 helper class 中有一些内容它允许使用这样的方法:
    public override int GetHashCode()
    {
        int hash = HashCodeHelper.Initialize();
        hash = HashCodeHelper.Hash(hash, LocalInstant);
        hash = HashCodeHelper.Hash(hash, Offset);
        hash = HashCodeHelper.Hash(hash, Zone);
        return hash;
    }
    

    helper 为您处理无效。所有这些都比每次需要计算哈希码时通过格式化创建字符串要好得多。

    关于.net - 考虑到开发人员的时间对 GetHashCode 进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14375061/

    相关文章:

    c# - 为什么我不能直接将自定义事件参数类传递到订阅我的事件的方法中?

    c# - 方法未找到 : 'System.Object Microsoft.EntityFrameworkCore.Infrastructure.IAnnotatable.get_Item(System.String)'

    c# - 如何在 C# 中连接到 Telnet 服务器?

    ruby - ruby 中的模拟系统调用

    c# - 如何对 POST 方法进行单元测试

    c# - .net 中的对象比较

    .net - 如何将 Azure 应用服务的访问权限限制为仅在 Azure Ad 的用户和组设置中添加的用户?

    unit-testing - 使用 Rhino Mocks 保存到存储库

    c# - 比较两个列表并忽略特定属性

    c# - List.Contains 未按预期工作