問題描述
我有一個建造者:
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;
}
}
在 mockito 中模擬構(gòu)建器會給我每個方法的 null.那么有沒有一種簡單的方法可以讓構(gòu)建器在每次函數(shù)調(diào)用時返回自身,而無需使用 when().thenReturn
模擬每個函數(shù)本身.
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
.
推薦答案
你可以使用RETURN_DEEP_STUBS 模擬鏈接 API.
You can use RETURN_DEEP_STUBS to mock a chaining API.
如果您知道調(diào)用構(gòu)建器的確切順序,以下是您將如何使用它的示例:
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
不幸的是,這不會為您提供一種模擬所有各種構(gòu)建器方法"的通用方式,因此它們總是返回這個,看看另一個答案是你需要那個.
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.
這篇關(guān)于如何用 mockito 模擬 builder的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!