单位使用Robolectric和Mockito进行Android服务层(Retrofit)

时间:2017-07-15 18:31:38

标签: android unit-testing mockito robolectric

我开发了一个集成了改造2.0的Android应用程序。我没有添加很少的服务调用,并希望对它进行写单元测试,

我决定使用Robolectric,因为它单独运行,我可以运行CI集成和模拟对象我决定使用Mockito

现在我有一个Api类并实现它

public interface NellyApi {

    // Get Api Access Token
    @FormUrlEncoded
    @POST("/oauth/token")
    Call<Authorization> requestApiToken(@Header("Authorization") String token,@FieldMap Map<String,String> fields);

    //Get Product by brand
    @Headers({
            "xx: x",
            "xx: x",
            "content-type: application/json",
    })
}

这是它的实现

    public class NellyWebService {

        private final String TAG = "NellyWebService";

        private NellyApi api;
        private static  NellyWebService service;
        private final String SERVICE_ENDPOINT = "URL";
        private Retrofit retrofit;
        private String authorizationToken;

        private NellyWebService(){

            retrofit =  new Retrofit.Builder()
                    .baseUrl(SERVICE_ENDPOINT)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();

            api = retrofit.create(NellyApi.class);

        }

        public static NellyWebService getInstance(){

            if(service == null){
                service = new NellyWebService();
            }
            return  service;
        }

        public void getApiAccessToken(){

            String clientId ="x";
            String clientSecret="xxx";
            String credentials = clientId+ ":" + clientSecret;

            String base64EncodedCredentials = Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
            String authHeader = "xx " + base64EncodedCredentials;


            Map<String, String> params = new HashMap();
            params.put("scope","xx");
            params.put("grant_type","xxx");



authorization = api.requestApiToken(authHeader,params);
    authorization.enqueue(new Callback<Authorization>() {
        @Override
        public void onResponse(Call<Authorization> call, Response<Authorization> response) {
            if(response.body() != null){
                Log.d(TAG,response.body().toString());
                authorizationToken = response.body().getAccessToken();
                //callBack.onResponseSuccess(response.code());
                statusCode = 200;
            }

        }
        @Override
        public void onFailure(Call<Authorization> call, Throwable t) {
            Log.d(TAG,t.toString());
            //callBack.onFail();
            statusCode = 200;
        }
    });

        }
    }

基本上我想编写测试用例来测试这个api是否有效,并检查它是否给出了正确的响应(输出数据与给定数据匹配)。

我该怎么做?怎么写我的单元测试来检查这个?

我已经为此编写了一个单元测试,但不清楚如何从这个

移动
 @RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = Build.VERSION_CODES.LOLLIPOP)
public class NellyWebServiceTest {


    private  NellyWebService apiImpl;

    @Captor
    private ArgumentCaptor<Callback<CountryListResponse>> cb;

    @Captor
    private ArgumentCaptor<ResponseCallBack> cb1;

    @Mock
    private Call<CountryListResponse> countryListCall;

    @Before
    public  void setUp(){
        MockitoAnnotations.initMocks(this);
        apiImpl = NellyWebService.getInstance();
    }

    @Test
    public void testApiAuthorization() throws  Exception{
    }

    @Test
    public void testGetCountryList() throws Exception{

        apiImpl.getApiAccessToken();
        await().until(newUserIsAdded());
        CountryListResponse res = apiImpl.getResponseInstance();

    }

    private Callable<Boolean> newUserIsAdded() {
        return new Callable<Boolean>() {
            public Boolean call() throws Exception {
                return apiImpl.getStatusCode()  != 0; // The condition that must be fulfilled
            }
        };
    }

}

0 个答案:

没有答案