首页 > 解决方案 > 如何在android中使用mockito编写单元测试进行改造

问题描述

我有一个简单的演示者,我想为其编写一个 Mockito 单元测试。

这是演示者类的代码,我在其中调用 api 并获取响应并通过使用接口向活动类(视图)发送响应:

class TrendingGifsPresenter(private val iTrendingGif: ITrendingGif, private val iShowError: IShowError) {


fun getTrendingGifs(offSet: Int) {
    val trendingGifs: Call<TrendingGifsModel> = ServiceRegistry.getInstance().getApi().getTrendingGifs("Z23s0syKe5njqYEIt8WjarxhNy9aZFaZ", offSet)

    trendingGifs.enqueue(object : Callback<TrendingGifsModel> {
        override fun onFailure(call: Call<TrendingGifsModel>?, t: Throwable?) {
            println(t!!.localizedMessage)
            iShowError.showError()
        }

        override fun onResponse(call: Call<TrendingGifsModel>?, response: Response<TrendingGifsModel>?) {
            if (response != null && response.isSuccessful && response.body() != null && response.body()!!.meta!!.status==200) {
                iTrendingGif.setTrendingGifs(response.body())
            }
        }
    })

}

fun getLoadMoreTrendingGifs(offSet: Int) {
    val trendingGifs: Call<TrendingGifsModel> = ServiceRegistry.getInstance().getApi().getTrendingGifs("Z23s0syKe5njqYEIt8WjarxhNy9aZFaZ", offSet)

    trendingGifs.enqueue(object : Callback<TrendingGifsModel> {
        override fun onFailure(call: Call<TrendingGifsModel>?, t: Throwable?) {
            println(t!!.localizedMessage)
            iShowError.showError()
        }

        override fun onResponse(call: Call<TrendingGifsModel>?, response: Response<TrendingGifsModel>?) {
            if (response != null && response.isSuccessful && response.body() != null && response.body()!!.meta!!.status == 200) {
                iTrendingGif.loadMoreTrendingGifs(response.body())
            }
        }
    })

}}

标签: androidunit-testingkotlinmockitoretrofit2

解决方案


推荐阅读