javaunit-testingmockito

How to mock a builder with mockito


I have a builder:

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

}

Mocking the builder in mockito will gives me null for every method. So is there an easy way to get the builder return itself on every function call, without mocking every function itself using when().thenReturn.


Solution

  • You can use RETURN_DEEP_STUBS to mock a chaining API.

    If you know the exact order your builder will be called, here's an example of how you would use it:

    Builder b = Mockito.mock(Builder.class, RETURNS_DEEP_STUBS);
    when(b.setName("a name").setAddress("an address")).thenReturn(b);
    assert b.setName("a name").setAddress("an address") == b; // this passes
    

    Unfortunately this won't give you a generic way of mocking "all the various builder methods" so that they always return this, see the other answer is you need that.