gpt4 book ai didi

c# - Rhino Mocks 约束和字典参数

转载 作者:行者123 更新时间:2023-11-30 14:43:37 28 4
gpt4 key购买 nike

您将如何检查接受字典的函数的参数?

IDictionary<string, string> someDictionary = new Dictionary<string, string> {
{"Key1", "Value1"},
{"Key2", "Value2"}
};

Expect.Call(delegate {someService.GetCodes(someDictionary);}).Constraints(...);

基本上,我想验证 GetCodes 的参数是否与变量“someDictionary”具有相同的值。

我忘了提到正在测试的方法会构建字典并将其传递给 someService.GetCodes() 方法。

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 Dictionary<string, string> {
{"Key 1", "Value 1a"},
{"Key 2a", "Value 2"}
};

someService.GetCodes(dict2); // This would fail!

}

因此,我想确保传递给 GetCodes 方法的字典包含与 Expect.Call... 方法中指定的相同的字典。

另一个用例是,也许我只想查看字典的键是否包含“Key 1”和“Key 2”,但不关心值......或者相反。

最佳答案

// 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)
);

更新:

这里是你如何断言参数值:

someService.AssertWasCalled(
x => x.GetCodes(
Arg<IDictionary<string, string>>.Matches(
dictionary =>
dictionary["Key1"] == "Value1" &&
dictionary["Key2"] == "Value2"
)
)
);

更新 2:

正如@mquander 在评论中所建议的,可以使用 LINQ 缩短之前的断言:

someService.AssertWasCalled(
x => x.GetCodes(
Arg<IDictionary<string, string>>.Matches(
dictionary =>
dictionary.All(pair => someDictionary[pair.Key] == pair.Value)
)
)
);

关于c# - Rhino Mocks 约束和字典参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1682777/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com