2009-11-05 68 views
3

如何檢查接受字典的函數的參數?Rhino Mocks約束和字典參數

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 specifed ...方法。

另一個用例可能是我可能只是想看看字典的鍵是否包含「鍵1」和「鍵2」,但不關心值......或者其他地方。

回答

6
// 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:

這裏是你如何可以斷言的參數值:

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

UPDATE2:

正如意見建議的@mquander中,以前的斷言可以縮短使用LINQ:

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

不知道這是我尋找的解決方案。我想檢查的是字典中的值,不一定是它們是相同的字典。 – 2009-11-06 19:18:00

+0

如果您檢查它是相同的字典引用,這意味着它具有相同的值,因此將值放入字典中是沒有必要的。我已經更新了我的帖子,以展示如何驗證模擬對象方法是否被某些特定參數調用的示例。 – 2009-11-07 00:06:14

+0

我對Rhino Mocks一無所知,但不能僅僅在上面的「UPDATE」中替換謂詞的主體,並將其改爲類似dictionary => dictionary.All(pair => someDict [pair.Key] == pair.Value)? – mquander 2009-11-07 00:24:16