I have a fairly simple GetHashCode() implementation in C# as per Jon Skeet's answer here. Here is my code:
public override int GetHashCode()
{
unchecked
{
int hash = 17;
if (Title != null)
{
hash = hash * 23 + Title.GetHashCode(); // Title is of type string
}
return hash;
}
}
When I run an NUnit test targeting this method through Visual Studio 2013's Test Explorer I get one value for the hash code and when I run it through ReSharper 8's Unit Test Explorer I get a different value.
Here is my unit test code:
[Test]
public void GetGetHashCode_WithLinkAndTitle()
{
const int expected = -1272954771;
var target = new Article
{
Title = "Rumble News"
};
var actual = target.GetHashCode();
Assert.AreEqual(expected, actual);
}
From VS 2013 I get actual == -1411317427 and from ReSharper I get actual == -1272954771.
Why are the values returned from GetHasCode() different across test runners and how can I make them consistent with each other?
You're probably using the 32-bit CLR in one test runner and the 64-bit CLR in another. The implementation of string.GetHashCode
differs between the two. You should not depend on them being consistent between runs - they only have to be consistent within a single process.
(It would be entirely reasonable for a GetHashCode
method to take a seed from a static field initialized randomly on class initialization. So each time you ran the executable you'd get a different set of hash codes - but they would still be consistent within a single app domain.)
See more on this question at Stackoverflow