如何使用Mockito在演示者中测试一个空隙方法



我有一个使用MVP模式构建的非常简单的应用程序。这是我的合同:

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;
    }
}

如何在主持人中测试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个基本步骤:首先您安排:因此创建自己的方案。例如,如果列表为null,则该示例是什么。第二:您行动:此步骤是您测试所需方法的地方。第三:断言:这是您验证或断言您的期望与给定代码匹配的地方。

相关内容

  • 没有找到相关文章

最新更新