There is such a method, it makes a request through VKApi and gets the user's avatar id

 private fun getPhotoIdByUser(userId: String) { val fields = "crop_photo" val request = VKApi.users().get(VKParameters.from(VKApiConst.USER_ID, userId, VKApiConst.COUNT, 1, VKApiConst.FIELDS, fields)) request.executeWithListener(object : VKRequest.VKRequestListener() { override fun onComplete(response: VKResponse?) { val id = response?.json?.getJSONArray("response") ?.getJSONObject(0)?.getJSONObject("crop_photo") ?.getJSONObject("photo")?.getString("id") } override fun onError(error: VKError?) { Log.e("tag", "error") } }) } 

I know what id should come back. But how to compare the actual result with the expected result if the method returns nothing? Is it possible to do something with the method so that testing becomes possible?

  • the idea of ​​onComplete () is not clear, gets the id and does not save it anywhere, what's the point? - keekkenen
  • @keekkenen meaning in passing the id to another method or returning the id from the method - Likhanov

1 answer 1

Yes, you need to make the method return something.

  1. If VkSdk has the ability to make synchronous requests - then use them manually launching methods not on the UI stream.
  2. If there is no possibility of a synchronous call, you will have to do it manually. For example, you can wrap all requests in Observable from either rxJava . Further you will have an opportunity to test them in the ways which are built in. Type myMethodWhichReturnsObservableWhichContainsVkSdkAsyncRequest().test().assertResult("SOME RESULT HERE, IE INT VALUE") . Read more here: Testing RxJava . Well, or even make the method work synchronously by calling .toBlocking() . But it will be a violation of the idea itself, and, we say, a crutch.
  3. Perhaps something will turn out if you use korutina from the language, which allow you to write asynchronous code in a synchronous style. But here I am not sure that this feature itself is still, like, experimental.