How to mock a builder with mockito

后端 未结 3 1561
醉话见心
醉话见心 2020-11-29 07:58

I have a builder:

class Builder{
     private String name;
     private String address;
     public Builder setName(String name){
         this.name = name;
         


        
3条回答
  •  借酒劲吻你
    2020-11-29 08:34

    The problem with using RETURN_DEEP_STUBS is that you'll get a different mock each time you call a method. I think from your question that you want to use a default Answer that actually returns the mock on which it was called, for each method that has the right return type. This could look something like the following. Note that I haven't tested this, so it may contain typos, but I hope that the intention is clear in any case.

    import static org.mockito.Mockito.RETURNS_DEFAULTS;
    import org.mockito.invocation.InvocationOnMock;
    import org.mockito.stubbing.Answer;
    
    public class SelfReturningAnswer implements Answer {
    
        public Object answer(InvocationOnMock invocation) throws Throwable {
            Object mock = invocation.getMock();
            if(invocation.getMethod().getReturnType().isInstance(mock)){
                return mock;
            }
            return RETURNS_DEFAULTS.answer(invocation);
        }
    }
    
    

    Then, when you create your mock, specify this as your default answer. This will make your mock return itself from each method that it can; but it will behave like an ordinary mock when you call a method whose return type is wrong for the mock.

    Create your mock like this

    Builder mockBuilder = mock( Builder.class, new SelfReturningAnswer());
    

    or create a constant for this class and write something like

    @Mock(answer = SELF_RETURNING) private Builder mockBuilder;
    

    Hope that helps.

    提交回复
    热议问题