how to throw an HttpException in Kotlin - retrofit 2 - unit test

Viewed 3240

I am writing a unit test and I want to throw an HttpException with an error code 409.

This is what I tried but it gives me an error

Using 'parse(String): MediaType?' is an error. moved to extension function

This is a kotlin file and Retrofit 2.6.0, and ResponseBody is okhttp3 - 3.12.12

What I have tried

 every(call.execute()).thenThrow(HttpException(
            Response.error<Any>(409, ResponseBody.create(
                MediaType.parse("plain/text"), ""
            ))
        ))

how can i solve this please

thanks R

3 Answers

For Kotlin: currently ResponseBody.create methods are deprecated (at least in OkHttp3 ver. 4.9.1). Following extension method can be used:

"raw response body as string".toResponseBody("plain/text".toMediaTypeOrNull())

i just throw this:

 throw HttpException(Response.error<ResponseBody>(500 ,ResponseBody.create(MediaType.parse("plain/text"),"some content")))

I've encountered this before. At some point, some dependencies of OkHttp3 changed, and the resulting error message isn't super helpful. What I believe you are looking for is the new .toMediaType() Kotlin extension function. So instead of:

ResponseBody.create(MediaType.parse("plain/text"), "")

Please try:

ResponseBody.create("plain/text".toMediaType(), "")

You'll likely need to import this extension. If your IDE doesn't automatically suggest it, please try importing via import okhttp3.MediaType.Companion.toMediaType.

Related