gpt4 book ai didi

android - 如何使用 Mockito 测试 Presenter 中的 void 方法?

转载 作者:行者123 更新时间:2023-11-29 23:03:27 24 4
gpt4 key购买 nike

我有一个使用 MVP 模式构建的非常简单的应用程序。这是我的契约(Contract):

public interface CitiesContract {
interface View {
void addCitiesToList(List<City> cityList);
}

interface Presenter {
void getCityList();
}

interface Model {
List<City> getCityList();
}
}

这是我的观点:

public class CitiesActivity extends AppCompatActivity implements CitiesContract.View {
private List<City> cityList = new ArrayList<>();

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cities);

CitiesPresenter presenter = new CitiesPresenter(this);
presenter.getCityList();
}

@Override
public void addCitiesToList(List<City> cities) {
cityList.addAll(cities);
}
}

这是我的演示者:

public class CitiesPresenter implements CitiesContract.Presenter {
private CitiesContract.View view;
private CitiesModel model;

public CitiesPresenter(CitiesContract.View view) {
this.view = view;
model = new CitiesModel();
}

@Override
public void getCityList() {
List<City> cityList = model.getCityList();
view.addCitiesToList(cityList);
}
}

这是我的模型:

public class CitiesModel implements CitiesContract.Model {
@Override
public List<City> getCityList() {
List<City> cityList = new ArrayList<>();
//Add 30 cities to the list
return cityList;
}
}

如何在 Presenter 中测试 getCityList() 方法?到目前为止,这是我尝试过的:

public class CitiesPresenterTest {
private CitiesContract.Presenter citiesPresenter;
@Mock
private CitiesContract.View citiesView;

public void setUp() {
MockitoAnnotations.initMocks(this);
citiesPresenter = new CitiesPresenter(citiesView);
}

@Test
public void getCityListTest() {
citiesPresenter.getCityList();
//What to do next???
}
}

最佳答案

好的,顺便说一句,这是个好问题。首先,您还需要模拟您的模型。第二:安排一些事情:例如 model.getCityList() 返回 null。之后,您可以使用 mockitos verify 运算符进行验证。示例:

when(model.getCityList()).thenReturn(null);
citiesPresenter.getCityList();
verify(view).addCitiesToList(null);

另一种情况可能与此类似,但列表为空:

List<City> citiesList = new ArrayList<>();

when(model.getCityList()).thenReturn(citiesList );
citiesPresenter.getCityList();
verify(view).addCitiesToList(citiesList);

另一个可以是这样,你可以自己构建一个假列表来测试它:

List<City> citiesList = new ArrayList<>();
list.add(City("name", "something else", "i don't know what atributes you have"));

when(model.getCityList()).thenReturn(citiesList );
citiesPresenter.getCityList();
verify(view).addCitiesToList(citiesList);

希望我有所帮助。

附加信息:当进行单元测试时,您的脑海中应该有 3 个基本步骤:首先,您安排:因此您创建自己的场景。例如,如果列表为空会怎样。第二:你行动:这一步是你测试你想要的方法的地方。第三:断言:这是您验证或断言您的期望与给定代码匹配的地方。

关于android - 如何使用 Mockito 测试 Presenter 中的 void 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56752872/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com