使用robolectric和mockito进行单元测试,以便在android中进行改造

时间:2015-05-21 13:21:53

标签: android unit-testing mockito retrofit robolectric

我正面临着如何编写改造测试代码的问题。代码如下。

MainActivity.java

import android.os.Bundle;
import java.util.List;
import gallery.com.brandlistview.Bird;
import retrofit.Callback;
import retrofit.client.Response;

public class MainActivity implements Callback<List<Bird>> {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Globals.getRestClient().getBirdClient().getBirdList(this);
    }

    @Override
    public void success(List<Bird> birds, Response response) {
    }

    @Override
    public void failure(--------) {
    }
}

Bird.java

public class Bird {
    private String image_url;
    public String getImage_url() {
        return image_url;
    }
    public void setImage_url(---------) {
        -----------
    }
}

Globals.java

public class globals{
    public static RestClient restClient;

    public static RestClient getRestClient() {
        return restClient; 
    }
    public static BirdClient getBirdClient() {
        return getRestClient().getBirdClient();
    }
}

RestClient.java

public class RestClient{
private BirdClient   mBirdClient;

public RestClient() {
   mBirdClient = new BirdClient(getBirdService());
}

public BirdClient getBirdClient() { return mBirdClient; }

public static BirdService getBirdService() {
   RestAdapter restAdapter = new RestAdapter.Builder()
         .setEndpoint(URL)
         .setLogLevel(RestAdapter.LogLevel.FULL)
         .build();

   return restAdapter.create(BirdService.class);
}
}

BirdClient.java

public class BirdClient{
private BirdService mAPIService;

public BirdClient(BirdService service) {
   assert service != null;
   mAPIService = service;
}
public void getBirdList(final Callback<List<Bird>> delegate) {
  ----------------------
}
}

BirdService.java

public interface BirdService {

   @GET(URL)
   void getBirdList(Callback<List<Bird>> objectManager);
}

我想编写测试代码来测试在成功回调getBirdList()之后List中的项目数是否等于15(例如),如图所示是MainActivity.java。另外,我正在使用Robolectric和Mockito库进行测试。我想从星期二开始写。请帮助。

1 个答案:

答案 0 :(得分:2)

我建议您不要测试服务器的实际请求是否正常,因为服务器响应可能会发生变化,运行测试时可能没有互联网,但是使用一些模拟数据进行测试。

这是一个例子,他将mockito与改造一起用于单元测试api功能:

http://www.mdswanson.com/blog/2013/12/16/reliable-android-http-testing-with-retrofit-and-mockito.html

祝你好运!