Pregunta

Today I wanna test my critical program with C#. In this program some properties will hash via GetHashCode() method. After implement parts of program, Unit Test project was added. Then I run the program in debug mode and copy hashed data to notepad to use for comparison on unit test project. After that run test method in debug mode and again get hashed data and copy it to notepad. In this case I saw that hash code of unique string are not them same in debug mode and unit test mode.

I don't know where it raised and how to solve this.

Is that a problem?

¿Fue útil?

Solución

This article on MSDN contains an explicit warning that you should not persist the hash code of strings. It is not guaranteed that the same string values will map to the same hash code outside of the application domain.

If two string objects are equal, the GetHashCode method returns identical values. However, there is not a unique hash code value for each unique string value. Different strings can return the same hash code.

The hash code itself is not guaranteed to be stable. Hash codes for identical strings can differ across versions of the .NET Framework and across platforms (such as 32-bit and 64-bit) for a single version of the .NET Framework. In some cases, they can even differ by application domain.

As a result, hash codes should never be used outside of the application domain in which they were created, they should never be used as key fields in a collection, and they should never be persisted.

Finally, do not use the hash code instead of a value returned by a cryptographic hashing function if you need a cryptographically strong hash. For cryptographic hashes, use a class derived from the System.Security.Cryptography.HashAlgorithm or System.Security.Cryptography.KeyedHashAlgorithm class.

For more information about hash codes, see Object.GetHashCode.

So for your test, I'd either rely on that the GetHashCode-implementation of String is correct or create and inject a mockable hash code provider that returns string.GetHashCode for normal code and is substituted by a mock when running tests. With "hash code provider", I mean an abstract class or interface that has a method that returns a hash code for a given string, e.g.:

internal interface IHashCodeProvider
{
    int ProvideHashCode(string stringValue);
}

A more lightweight approach is to inject a function that returns the has code, e.g.: Func<string, int>. Default function would be x => x.GetHashCode().

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top