【发布时间】:2015-01-08 19:32:40
【问题描述】:
根据 Jon Skeet 的回答 here,我在 C# 中有一个相当简单的 GetHashCode() 实现。这是我的代码:
public override int GetHashCode()
{
unchecked
{
int hash = 17;
if (Title != null)
{
hash = hash * 23 + Title.GetHashCode(); // Title is of type string
}
return hash;
}
}
当我通过 Visual Studio 2013 的 Test Explorer 运行针对此方法的 NUnit 测试时,我得到一个哈希码值,当我通过 ReSharper 8 的 Unit Test Explorer 运行它时> 我得到了不同的价值。
这是我的单元测试代码:
[Test]
public void GetGetHashCode_WithLinkAndTitle()
{
const int expected = -1272954771;
var target = new Article
{
Title = "Rumble News"
};
var actual = target.GetHashCode();
Assert.AreEqual(expected, actual);
}
从 VS 2013 我得到实际 == -1411317427,从 ReSharper 我得到实际 == -1272954771。
为什么从 GetHasCode() 返回的值在不同的测试运行器之间存在差异,我怎样才能使它们彼此一致?
【问题讨论】:
-
你看到的值是什么,
Title中的字符串是什么,Title的hashcode是什么? -
谢谢@PatrickQuirk。我在问题正文中添加了详细信息。
-
在对
GetHashCode进行单元测试时,您应该只验证在两个相等的对象上调用它会返回相同的值。这样您就可以在不中断测试的情况下更改实现。
标签: c# unit-testing visual-studio-2013 resharper