0

I have developed a android application which integrated retrofit 2.0 Not i have added few service calls and wants write unit test for it ,

I've decided to use Robolectric since it separately run and i can run with CI integration and to mock objects i decide to use Mockito

Now i have a Api class and implementation of it

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",
    })
}

and this is the implementation of it

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

        }
    }

Basially i want to write test cases to test whether this api works or not and to check the whether it gives the proper response (Output data matches with given data ).

How can i do that , ? How should write my unit test to check this ?

Ive already written a unit test for this but not clear how to move from this

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

}
Mr.G
  • 1,275
  • 1
  • 18
  • 48
  • It would be a lot easier if the `getApiAccessToken` method accepted a callback so you can tell when it's done. But what answer are you expecting? Are you looking for someone to write the tests for you? Have you gone through a tutorial on Robolectric and/or Mockito? Have you written any test code? – nasch Jul 16 '17 at 01:34
  • @nasch yes i did , my question is im not clear on few things , like which method do i have to test? getApiAccessToken() or requestApiToken() – Mr.G Jul 16 '17 at 03:09
  • @nasch already made a class , can u point out what am i missing ? – Mr.G Jul 16 '17 at 03:29
  • No, you don't need to test `requestApiToken` directly because `getApiToken` already calls it. But again I recommend a callback parameter to `getApiToken` so you can easily get back the result. Also look into Awaitility for asynchronous operations. If you don't do something about it your test will complete before the async operation does. https://github.com/awaitility/awaitility – nasch Jul 16 '17 at 23:32
  • integrated awailitiy and yes needed to add it sync this is a async call , but when i run case , it lags , @nasch – Mr.G Jul 17 '17 at 14:21
  • and as i know . callback wont calls in test classes right ? – Mr.G Jul 17 '17 at 14:22
  • They absolutely will work in test classes. What do you mean it lags? – nasch Jul 17 '17 at 15:17
  • let me update the answer , what i did i put a function to wait . . – Mr.G Jul 17 '17 at 15:19
  • @nasch gives org.awaitility.core.ConditionTimeoutException: Condition returned by method "newUserIsAdded" in class com.example.ganidu.nellyapisample.NellyWebServiceTest was not fulfilled within 10 seconds. – Mr.G Jul 17 '17 at 15:32

0 Answers0