2016-11-02 49 views
3

我有方法的類:的Mockito參數匹配使用多個參數

class URAction { 
     public List<URules> getUrules(Cond cond, Cat cat) { 
      ... 
     } 
} 

我想創建它的模擬:

@Mock 
URAction uraMock; 

@Test 
public void testSth() { 
    Cond cond1; 
    Cat cat1; 
    List<URule> uRules; 

    // pseudo code 
    // when uraMock's getUrules is called with cond1 and cat1 
    // then return uRules 
} 

的問題是,我可以讓模擬返回uRules只有一個參數:

when(uraMock.getUrules(argThat(
     new ArgumentMatcher<Cond>() { 

      @Override 
      public boolean matches(Object argument) { 
       Cond cond = ((Cond) argument); 
       if (cond.getConditionKey().equals(cond1.getConditionKey()) 
        return true; 
       return false; 
      } 

     } 
    ))).thenReturn(uRules); 

不知道如何傳遞第二個參數,即貓在上面的時候調用。

任何幫助將不勝感激。

感謝

+0

一個解決辦法是使用'時(uraMock.getUrules(任何(Cond.class),任(Cat.class).thenAnswer(新的答案(){})',檢查ARGS在實施答案。看http://site.mockito.org/mockito/docs/current/org/mockito/stubbing/Answer.html –

+0

這似乎是一個可行的解決方案。如何紀念這個作爲答案?它只是在註釋。 – user1539343

+0

讓我們這樣做:根據我的評論添加一個答案並接受它,這可能會給你一些代表;) –

回答

3

你能嘗試添加另一個argThat(argumentMatcher)的第二個參數匹配?

而且,我覺得這是更好地沒有匿名類定義爲一個方法,當你做了沒有內聯。然後你可以將它用於verify()。

你的方法應該是這樣的

ArgumentMatcher<Cond> matcherOne(Cond cond1){ 
    return new ArgumentMatcher<Cond>() { 
     @Override 
     public boolean matches(Object argument) { 
      Cond cond = ((Cond) argument); 
      if (cond.getConditionKey().equals(cond1.getConditionKey()) 
       return true; 
      return false; 
     } 
    } 
} 

ArgumentMatcher<OtherParam> matcherTwo(OtherParam otherParam){ 
    return new ArgumentMatcher<OtherParam>() { 
     @Override 
     public boolean matches(Object argument) { 
      OtherParam otherParam = ((OtherParam) argument); 
      if (<some logic>) 
       return true; 
      return false; 
     } 
    } 
} 

然後,你可以打電話給你的方法,這樣,

when(uraMock.getUrules(argThat(matcherOne(cond1)), argThat(matcherTwo(otherParam)))).thenReturn(uRules); 

當時我你可以調用verify,要檢查,如果你當法真正得到叫做

verify(uraMock).getUrules(argThat(matcherOne(cond1)), argThat(matcherTwo(otherParam))); 

如果你不關心其他參數,你c一個待辦事項,

when(uraMock.getUrules(argThat(matcherOne(cond1)), argThat(any()))).thenReturn(uRules); 

有關詳細信息,請參閱:http://site.mockito.org/mockito/docs/current/org/mockito/stubbing/Answer.html

希望這是明確的..祝你好運!

+0

@ user1539343如果您對此答案感到滿意,請標記爲已接受:) –