How do I change the default return value for Strings in Mockito?

前端 未结 1 1529
滥情空心
滥情空心 2021-01-11 11:48

This issue from 2010 hints at what I\'m trying to do.

I\'m working on a unit test which exercises code that requires many mocked objects to do what it needs to do (t

相关标签:
1条回答
  • 2021-01-11 12:16

    I was able to completely answer my own question.

    In this example an address with the Locality of Louisville is generated while the other fields look like "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);
               }
           }
    }
    
    0 讨论(0)
提交回复
热议问题