Today I changed to use StringDictionary instead of Dictionary<string,string> in my code, but old unit test failed. So I write a small unit test to test this.
Here is my small test:
using Rhino.Mocks;
using NUnit.Framework;
//using CustomDictionary = System.Collections.Specialized.StringDictionary;
using CustomDictionary = System.Collections.Generic.Dictionary<string, string>;
namespace ConsoleApplication1
{
public interface ITest
{
void DoSth(CustomDictionary dic);
}
public class OneTest : ITest
{
public void DoSth(CustomDictionary dic) {/*do nothing*/}
}
[TestFixture]
public class TestClass
{
[Test]
public void Test1()
{
var mockRepository = new MockRepository();
var test = mockRepository.StrictMock<ITest>();
using (mockRepository.Record())
{
Expect.Call(() => test.DoSth(new CustomDictionary { { "Test", "Test1" } }));
}
test.DoSth(new CustomDictionary { { "Test", "Test1" } });
mockRepository.VerifyAll();
}
}
}
If I use Dictionary<string,string>, the test will pass, but when I use StringDictionary, the test failed.
What’s the problem here?
Problem goes from
StringDictionaryinstances comparison. There is no overriddenEqualsmethod, thus instances compared not by content, but by references. If you will use same instance, test will pass:You can override
Equalson yourCustomDictionaryclass to make your original test pass:BTW I hope this is not your real test, because here you are testing mock, instead of testing your code.
WHY YOUR CODE WORKS WITH DICTIONARY:
As I understand RhinoMocks implementation,
Rhino.Mocks.Impl.Validateclass used for arguments validation. You can take a look on it’sArgsEqualmethod implementation:I leave to you details of
RecursiveCollectionEqual, but interesting part there is arguments comparison:As you can see, if argument is
ICollectionthen Rhino goes deeper to compare expected and actual collections.DictionaryimplementsICollection, butStringDictionarydoes not. Thus arguments ofStringDictionarytypes compared only by reference.UPDATE: Didn’t notice, that you have an alias. Just inherit from type instead, and you will be able to override
Equals: