How to mock a builder with mockito

后端 未结 3 1565
醉话见心
醉话见心 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:27

    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.

提交回复
热议问题