【问题标题】:Rhino Mocks constraints and Dictionary parametersRhino Mocks 约束和字典参数
【发布时间】:2009-11-05 18:55:13
【问题描述】:

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

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... 方法中指定的字典相同的字典。

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

【问题讨论】:

    标签: c# .net unit-testing mocking rhino-mocks


    【解决方案1】:
    // 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 在 cmets 中所建议的,可以使用 LINQ 缩短之前的断言:

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

    【讨论】:

    • 不确定这是我正在寻找的解决方案。我要检查的是字典中的值,不一定是同一个字典。
    • 如果您检查它是否是同一个字典引用,这意味着它具有相同的值,因此不需要将值放入字典中。我更新了我的帖子,展示了一个示例,说明如何验证已使用某些特定参数调用了模拟对象方法。
    • 我对Rhino Mocks一无所知,但你不能只替换上面“更新”中谓词的主体并将其更改为dictionary => dictionary.All(pair => someDict [pair.Key] == pair.Value) ?
    • 谢谢达林。该更新正是我想要的。谢谢!
    • @mquander,是的,dictionary.All 确实可以工作。我添加了一个 UPDATE2。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多