Wednesday, April 2, 2025

How to mock Retrofit2 response Call in a unittest

Introduction

To mock a Retrofit2 call which returns Call<Void?> in the interface client like this:

    @POST("/events")

    fun registerEvent(@Body requestDto: EventRequestDto): Call<Void?>

is not super-obvious, since it can show this error when invoked:

    Cannot invoke "retrofit2.Call.request()" because "call$iv" is null

    java.lang.NullPointerException: Cannot invoke "retrofit2.Call.request()" because "call$iv" is null

Solution

    val mockedResponseRegisterEvent: Call<Void?> = retrofit2.mock.Calls.response(null)
    every { retrofitEventServiceClient.registerEvent(any()) } returns mockedResponseRegisterEvent