How to unit test retrofit call?

How to unit test retrofit call?

how to mock retrofit call
unit test retrofit callback
how to unit test api calls
retrofit mockwebserver
retrofit mock response
unit test retrofit kotlin
okhttp interceptor unit test
how to check api calls in android

For Example I have a retrofit interface such as:

interface SampleService {
    fun getSomething(@body someBody: SomeBody)
}

Now I have a class which uses this interface such as:

class UserRequester(val service: SampleService) {
     fun doGetSomething(someValue: String) {
         val response = service.getSomething(SomeBody(someValue))
         // ...
     }
 }

I want to test this class but dont know how to mock it.

I'm trying the following:

val mockSampleService = mock()
val userRequester = UserRequester(mockSampleService)
val requestBody = SomeBody(someString))
  when(mockSampleService.getSomething(requestBody)).return(myExpectedValue)
....

My problem is that since I create the request object inside the function, I could not make the mock when().thenReturn() to work since i am technically passing two different object.

How should I test this? Thanks in advance.


The mocking problem (UserRequester)

You are not able to mock the mockSampleService method because your class is creating the SomeBody object and is different from the SomeBody object you are creating in your test.

Now you have 2 options:

  1. Use Mockito.any() in your test, in this way you basically say that whatever your method is gonna use as parameter you will return the mocked behaviour
  2. Use a factory that given a someString returns you a SomeObject like this:

// the factory
class SomeObjectFactory{

    fun createSomeObject(someString: String): SomeObject {
        return SomeObject(someString)
    }

}

//the class
class UserRequester(
val service: SampleService, val factory: SomeObjectFactory
) {
     fun doGetSomething(someValue: String) {
         val response = service.getSomething(factory.createSomeObject(someValue))
         // ...
     }
 }

//the test
class MyTest{

    @Test
    fun myTestMethod(){
        val mockSampleService = mock()
        val factory = mock()
        val someBody = mock()
        val userRequester = UserRequester(mockSampleService, factory)
        `when`(factory.createSomeObject(someString)).thenReturn(someBody)

  `when`(mockSampleService.getSomething(someBody)).thenReturn(myExpectedValue)
    //rest of the code
    }

}

The second approach is the cleanest one.

Testing Retrofit calls (SampleService)

I wouldn't unit test a Retrofit call.

When you are dealing with frameworks, apis, databases, shared preferences is always preferable to do integration tests instead of unit tests.

In this way you are actually testing that your code is working with the outside world.

I suggest you to test Retrofit calls with MockWebServer (it's a library from Square, the same company that developed OkHttp and Retrofit).

This read may be also helpful.

How to unit test Retrofit api calls?, I test my Retrofit callbacks using Mockito, Robolectric and Hamcrest libraries. First of all, set up lib stack in your module's build.gradle: Testing Retrofit calls (SampleService) I wouldn't unit test a Retrofit call. When you are dealing with frameworks, apis, databases, shared preferences is always preferable to do integration tests instead of unit tests. In this way you are actually testing that your code is working with the outside world.


The problem is that there is static dependency on SomeBody's constructor:

val response = service.getSomething(SomeBody(someValue))

What you could do to have control over the instantiation of SomeBody is to use a "provider" or "factory" object, you can inject it in the constructor and invoke it at the right time:

interface SampleService {
    fun getSomething(someBody: SomeBody)
}

open class SomeBody(val body: String)

open class UserRequester(
    val service: SampleService,
    val someBodyProvider: (String) -> SomeBody
) {

    fun doGetSomething(someValue: String) {
        val response = service.getSomething(someBodyProvider(someValue))
    }
}

And mock it in your tests:

val someValue = "foo"
val sampleService: SampleService = mock()
val someBody: SomeBody = mock()
val someBodyProvider: (String) -> SomeBody = mock {
    on { invoke(someValue) }.thenReturn(someBody)
}
val userRequester = UserRequester(sampleService, someBodyProvider)

userRequester.doGetSomething("foo")

verify(sampleService).getSomething(someBody)
verify(someBodyProvider).invoke(someValue)

I used an anonymous function but you might as well make it an interface.

Unit testing API requests on Android, In this article I want to show you a tutorial on how I decided to test the API Request layer using RxAndroid, Retrofit, Mockito and the Model View  Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. Unit testing Retrofit api call with Mockito


Probably SomeBody is a plain value object, since Retrofit requests work with value objects. If you define the equals method for the SomeBody class then the eq matcher will work, and you can write using mockito-kotlin:

whenever(mockService.getSomething(eq(SomeBody(someString)))).thenReturn(stubbedResult)

Actually, you can omit the eq matcher, Mockito will use the equals method for matching.

If SomeBody is a Kotlin data class then the equals method is automatically defined by comparing the fields.

If for some reason you don't want to rely on equals, then you can use the argThat matcher defined in mockito-kotlin:

whenever(mockService.getSomething(argThat { theField == someValue })).thenReturn(stubbedResult)

Test REST APIs with Kotlin, Retrofit, and JUnit5, To test the purchasing of credits we'll use Retrofit to call our API and JUnit to verify the results. Retrofit is a really clever HTTP library from Square . You use interfaces and annotations describe an API and then build it into a concrete client using Retrofit reflection. 1) At the start of your test method, replace the AuthAPI's loginService object with your mockApi object, then call AuthAPI.Login (). 2) Use verify () as you already are to check that the function has been called. 3) Create a sample AuthObject and pass it to the cb.getValue ().success () function.


How to Unit test Retrofit api calls, I am trying to integrate Unit test cases for every chunk of code possible.But I am facing issues while adding test cases for api calls that are made through retrofit. //MockResponse can also be customized with different parameters //to match your test needs mockWebServer.enqueue(new MockResponse().setBody("your json body")); YourRetrofitService service = retrofit.create(YourRetrofitService.class); //With your service created you can now call its method that should //consume the MockResponse above.


How to properly unit test Retrofit calls with coroutines. : androiddev, I just started learning unit testing in Android. I would like to see a worthy example on testing my Retrofit calls with coroutines. Well I'm giving my personal  how to test the server call with Mockito, Retrofit and RxJava In this example you can learn how to test server call with Mockito and RxJava, We need this elements: 1. Service 2. RemoteDataSource 3. RemoteDataSourceTest Simple Service: For RemoteDataSource … Continue reading →


Retrofit 2 - Mocking HTTP Responses – Rebecca Franks, enqueue() get called? For example, I want to mock an api response after clicking a “Login” button which calls /api/login endpoint. This separation of concerns is very friendly to writing unit tests since each layer can have mocked dependencies and we can test for happy-cases as well as disastrous ones! Let’s take a simple example of a screen which shows a list of blogs that are fetched from a remote server. I’m using RxJava2 and Retrofit, OkHttp for this