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
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
I know that this question is asked hundreds of time, I've checked more than 30 answer and none worked for me.
I'm running a unit test in android studio using Kotlin. I'm trying to build a JSONObject using a String.
The method I'm using to build a simple json object is always throwing Cannot evaluate org.json.JSONObject.toString().
The string I'm using definitely have a valid Json format.
Is this a bug in android or what??
Here's the method I'm using:
fun createTaskJson(): JSONObject {
val jsonString =
"{\"id\":138,\"title\":\"G0102-025\",\"type\":\"New Land Evaluation\",\"taskCreationDate\":\"28/01/2020\",\"taskDeliveryDate\":\"02/02/2020\",\"taskCreationTime\":\"05:15 AM\"}"
val realJson = JSONObject(jsonString)
return realJson
}
UPDATE 1:
Please note that also creating an empty JSONObject will throw the same error !!
UPDATE 2:
After checking the stacktrace, I've found the following error:
Method toString in org.json.JSONObject not mocked.
I've googled it and the solution was to add the following configuration into my build.gradle file:
testOptions {
unitTests.returnDefaultValues = true
}
But adding this made the returned JSONObject null instead of throwing an exception, even though my string is formatted correctly.
After the updates mentioned in the question above. And after lots of searching. I found out the following:
The solution was in adding the following line into build.gradle file:
implementation group: 'org.json', name: 'json', version: '20190722'
I don't know why, but it's like android have an object with names JSONArray and JSONObject but when adding the implementation to the build.gradlefile. It handles JSONObject and JSONArray in another way.
Because after adding the statement to the gradle file, the following warning will be giving by android:
json define classes that conflict with classes now provided by Android
i'm migrating from okhttp 3.14 to okhttp4, accordings to migration guide, when replacing "response.body()?" call to "response.body?" IDE shows error " Cannot access 'body': it is package-private in 'Response' " at last line of code
val request = Request.Builder().url(url).build()
val response = coreNetwork.getOkHttp().newCall(request).execute()
val stream = response.body?.source()?.inputStream()
if i'm trying "response.body()?" call, shows error " Using 'body(): ResponseBody?' is an error. moved to val " as expected.
Solved, i'm start watching to what version of okhttp linked every import, and one interface linked to okhttp-3.12.0.jar. This interface belongs to separate gradle module, and i found that i forgot add a dependency ' implementation "com.squareup.okhttp3:okhttp:4.2.2" ' to .gradle file of that module. (in that case class should not found okhttp dependency at all, but somehow found old version and depends on it)
This is an expected error message looking at the code for Response.kt in the 4.2.x version of the branch:
#JvmName("-deprecated_body")
#Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "body"),
level = DeprecationLevel.ERROR)
fun body(): ResponseBody? = body
so the solution would be to call response.body? which it looks like you are already doing...
see: https://github.com/square/okhttp/blob/okhttp_4.2.x/okhttp/src/main/java/okhttp3/Response.kt#L202 for details
The app defines constants in a Kotlin singleton object:
#file:JvmName("APIConstants")
package com.myapp.api
object APIConstants {
const val HTTP_RESPONSE_CODE_NOT_AUTHORIZED = 401
etc....
}
They are then used in another class:
import com.myapp.api.APIConstants.HTTP_RESPONSE_CODE_NOT_AUTHORIZED
etc ...
class API {
private fun returnBadResponse(response: Response<*>, callback: ApiAuthListener<*>) {
if (response.code() == HTTP_RESPONSE_CODE_NOT_AUTHORIZED) {
callback.onBadAuthToken()
} else {
callback.onFailure(response.message(), getServerError(response))
}
}
In this class Android Studio (3.0 beta) provided a hint to add the import for the constant, and it does not give any indication of a problem (no red underlines etc, and the constant reference in the method is shown in purple italic text indicating it has been resolved) but when I build the project I get this:
Error: Unresolved reference: HTTP_RESPONSE_CODE_NOT_AUTHORIZED
I've tried clearing the IDE cache and restarting it, and doing a clean build, which make no difference. I've tried removing the #JvmName annotation and even placing the const values in the root of the file with no containing object but neither allows a build.
Why is the class failing to reference the constant, especially when the IDE strongly suggests it can resolve it?
And the solution is.... to make very sure all Kotlin source files have a .kt file extension! In this case the APIConstants file was called "APIConstants" and not "APIConstants.kt" which appears to mean the IDE was able to resolve references based on the content of the file, but the build tools could not. Confusingly Android Studio showed a Kotlin K icon on the filename despite the lack of a .kt extension.
I have an android app with Realm and some Realm Module that help me to isolate synced Realm and i decide to migrate from Java to Kotlin.
#RealmModule(classes = arrayOf(Category::class, Product::class))
private class ShopModule
fun getShop(user: SyncUser, path: String): RealmConfiguration {
return SyncConfiguration.Builder(user, path)
.modules(ShopModule())
.build()
}
function getShop return RealmConfiguration to use in Realm.getInstance().
After some converting show me some error when build() has occurred:
io.realm.exceptions.RealmException: Could not find io.realm.ShopModuleMediator
please help me to continue my migration. I can't understand what's wrong because this method works for me in java.
UPDATE:
After good Q&A in comments and so many change and try in my project i found when using kotlin in my project ShopModuleMediator was not generated and when convert app project from Java to Kotlin project has worked befor clean Project.
🎉🎉 Congratulation with release Realm Java 4.1.0 this problem has been resolved and i share my test project you can see result but an important note that for using in instant app you must use https network and can't use http in instant app and i share another app that work when run in app mode but when run in instantapp has occurred an error : not permitted by network security policy this is because using http in authentication url.
I want create a REST client using AndroidAnnotations
When define converters on #Rest annotation, I receive the following compile error:
The converter class must be a subtype of org.springframework.http.converter.HttpMessageConverter RestClient.java
I use this libraries:
/libs
androidannotations-api-2.7.1.jar
gson-2.2.4.jar
jackson-core-asl-1.9.13
jackson-asl-0.9.5
jackson-mapper-asl-1.9.13
spring-android-auth-1.0.1.RELEASE.jar
spring-android-core-1.0.1.RELEASE.jar
spring-android-rest-template-1.0.1.RELEASE.jar
/compile-libs
androidannotations-2.7.1.jar
My source is similar to the example androidannotations
package com.sinffredy.spring;
import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter;
import com.googlecode.androidannotations.annotations.rest.Get;
import com.googlecode.androidannotations.annotations.rest.Rest;
#Rest(rootUrl = "http://my.url/ajax/services", converters = { MappingJacksonHttpMessageConverter.class })
public interface RestClient
{
#Get("/.do?valor={search}")
Respuesta getRespuesta(String search);
}
Thanks in advance !!!
I solved it!!! Only change my Eclipse. I was using Helios with Android Development Toolkit
Now I dowload The Android SDK than includes Eclipse + ADT plugin. Use my old workspace with my proyect and all work fine!!!.
It seems to be the same issue than this one. Sadly I still can't reproduce this bug.
Just to be sure, could you test by adding spring-android-rest-template in your annotation processing factory path ?