2013-04-02 55 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); 
      } 
     } 
} 
相关问题