2013-04-02 54 views
9

This issue from 2010 hints at what I'm trying to do.如何更改Mockito中字符串的默認返回值?

我正在進行單元測試,該練習需要許多模擬對象來執行需要做的事情(測試HTML + PDF渲染)。爲了讓這個測試成功,我需要生成許多模擬對象,並且每個對象最終都會將一些字符串數據返回給正在測試的代碼。

認爲我可以通過實施無論是我自己的Answer類或IMockitoConfiguration做到這一點,但我不知道如何實現這些,所以它們只是影響其返回字符串的方法。

我覺得下面的代碼接近我想要的。它拋出一個演員例外,java.lang.ClassCastException: java.lang.String cannot be cast to com.mypackage.ISOCountry。我認爲這意味着我需要默認或限制Answer隻影響String的默認值。

private Address createAddress(){ 
    Address address = mock(Address.class, new StringAnswer()); 

    /* I want to replace repetitive calls like this, with a default string. 
    I just need these getters to return a String, not a specific string. 

    when(address.getLocality()).thenReturn("Louisville"); 
    when(address.getStreet1()).thenReturn("1234 Fake Street Ln."); 
    when(address.getStreet2()).thenReturn("Suite 1337"); 
    when(address.getRegion()).thenReturn("AK"); 
    when(address.getPostal()).thenReturn("45069"); 
    */ 

    ISOCountry isoCountry = mock(ISOCountry.class); 
    when(isoCountry.getIsocode()).thenReturn("US"); 
    when(address.getCountry()).thenReturn(isoCountry); 

    return address; 
} 

//EDIT: This method returns an arbitrary string 
private class StringAnswer implements Answer<Object> { 
    @Override 
    public Object answer(InvocationOnMock invocation) throws Throwable { 
     String generatedString = "Generated String!"; 
      if(invocation.getMethod().getReturnType().isInstance(generatedString)){ 
       return generatedString; 
      } 
      else{ 
       return Mockito.RETURNS_DEFAULTS.answer(invocation); 
      } 
     } 
} 

如何設置Mockito爲返回String的模擬類上的方法默認返回生成的String? I found a solution to this part of the question on SO

對於額外的積分,我怎樣才能使生成的值是一個字符串形式爲Class.methodName?例如"Address.getStreet1()"而不是隻是一個隨機的字符串?

回答

8

我能夠完全回答我自己的問題。

在這個例子中,生成了Louisville地點的地址,而其他字段看起來像「address.getStreet1();」。

private Address createAddress(){ 
    Address address = mock(Address.class, new StringAnswer()); 

    when(address.getLocality()).thenReturn("Louisville"); 

    ISOCountry isoCountry = mock(ISOCountry.class); 
    when(isoCountry.getIsocode()).thenReturn("US"); 
    when(address.getCountry()).thenReturn(isoCountry); 

    return address; 
} 

private class StringAnswer implements Answer<Object> { 
    @Override 
    public Object answer(InvocationOnMock invocation) throws Throwable { 
      if(invocation.getMethod().getReturnType().equals(String.class)){ 
       return invocation.toString(); 
      } 
      else{ 
       return Mockito.RETURNS_DEFAULTS.answer(invocation); 
      } 
     } 
} 
相關問題