Rhino Mocks constraints and Dictionary parameters
How would you check the parameters on a function that accepts a Dictionary?
IDictionary<string, string> someDictionary = new Dictionary<string, string> {
{"Key1", "Value1"},
{"Key2", "Value2"}
};
Expect.Call(delegate {someService.GetCodes(someDictionary);}).Constraints(...);
Basically, I want to verify that the parameter for GetCodes has the same values as the variable "someDictionary".
I forgot to mention that the method being tested builds the dictionary and passes that to the someService.GetCodes() method.
public void SomeOtherMethod() {
IDictionary<string, string> dict = new Dictionary<string, string> {
{"Key 1", "Value 1"},
{"Key 2", "Value 2"}
};
someService.GetCodes(dict); // This would pass!
IDictionary<string, string> dict2 = new Dict开发者_运维知识库ionary<string, string> {
{"Key 1", "Value 1a"},
{"Key 2a", "Value 2"}
};
someService.GetCodes(dict2); // This would fail!
}
so, I want to make sure the dictionary passed to the GetCodes method contain the same ones as the one specifed in the Expect.Call... method.
Another use case would be that maybe I just want to see if the keys of the dictionary contain "Key 1" and "Key 2", but don't care about the values... Or the othe rway around.
// arrange
IDictionary<string, string> someDictionary = new Dictionary<string, string> {
{ "Key1", "Value1" },
{ "Key2", "Value2" }
};
ISomeService someService = MockRepository.GenerateStub<ISomeService>();
// act: someService needs to be the mocked object
// so invoke the desired method somehow
// this is usually done through the real subject under test
someService.GetCodes(someDictionary);
// assert
someService.AssertWasCalled(
x => x.GetCodes(someDictionary)
);
UPDATE:
Here's how you could assert argument values:
someService.AssertWasCalled(
x => x.GetCodes(
Arg<IDictionary<string, string>>.Matches(
dictionary =>
dictionary["Key1"] == "Value1" &&
dictionary["Key2"] == "Value2"
)
)
);
UPDATE2:
As suggested by @mquander in the comments, the previous assert could be shortened using LINQ:
someService.AssertWasCalled(
x => x.GetCodes(
Arg<IDictionary<string, string>>.Matches(
dictionary =>
dictionary.All(pair => someDictionary[pair.Key] == pair.Value)
)
)
);
精彩评论