如何在Mockito中更改字符串的默认返回值?

2010年的这个问题暗示了我正在努力做的事情。

我正在进行unit testing,该测试运行代码,需要许多模拟对象来完成它需要做的事情(测试HTML + PDF渲染)。 为了使这个测试成功,我需要生成许多模拟对象,并且每个对象最终都会将一些String数据返回给被测试的代码。

我可以通过实现我自己的Answer类或IMockitoConfiguration来实现这IMockitoConfiguration ,但我不确定如何实现它们,因此它们只会影响返回字符串的方法。

我觉得以下代码接近我想要的。 它抛出一个强制转换exception, 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 { @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); } } } 

如何为返回String的模拟类上的方法设置Mockito以返回生成的String? 我找到了关于SO的这部分问题的解决方案

对于额外的点,我如何使该生成的值为Class.methodNameforms的Class.methodName ? 例如"Address.getStreet1()"而不仅仅是一个随机字符串?

我能够完全回答我自己的问题。

在此示例中,生成了具有路易斯维尔位置的地址,而其他字段看起来像“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 { @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); } } }