我有一个执行网络请求的Android应用。我在应用程序中使用Wiremock进行仪器测试和改造。
该请求是这样嘲笑的:
stubFor(
get(urlMatching("/hello/world"))
.willReturn(
aResponse()
.withStatus(HttpURLConnection.HTTP_OK)
.withHeader("Content-Type", "text/plain")
.withBody(expectedServerResponse)
)
)
改造界面:
interface HelloWorldService {
@GET("/hello/world")
fun getHelloWorld(): Call<ResponseBody>
}
执行请求的应用程序代码:
val helloWorldService =
Retrofit.Builder()
.baseUrl(intent.getStringExtra(EXTRA_BASE_URL))
.client((application as MyApplication).createRetrofitHttpClient())
.build()
.create(HelloWorldService::class.java)
helloWorldService.getHelloWorld().enqueue(object : Callback<ResponseBody> {
override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
textView.text = if (response.isSuccessful) {
response.body()?.string()
} else {
response.message()
}
}
override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
textView.text = t.message
}
})
当模拟的响应的内容长度很大(超过256个字符),并且测试在魅族Note 5上运行时,wiremock会找到响应并看起来像将要发送
200
响应,正如我在logcat日志中看到的那样:Matched response definition:
{
"status" : 200,
"body" : "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"headers" : {
"Content-Type" : "text/plain"
}
}
Response:
HTTP/1.1 200
Content-Type: [text/plain]
Matched-Stub-Id: [a45b21c9-95f6-45fa-a7c3-acf473485fb6]
但是,该应用程序实际上会收到一个
500
错误代码,并在错误响应中显示以下消息:No interface method isAsyncStarted()Z in class Ljavax/servlet/http/HttpServletRequest; or its super classes (declaration of 'javax.servlet.http.HttpServletRequest' appears in /system/framework/meizu2_jcifs.jar)
最佳答案
问题在于,wiremock和魅族都嵌入了javax.servlet
类,但是版本不同(不兼容)。一种解决方法是重新放置(更改软件包名称)wiremock嵌入的javax.servlet
类。
而不是像这样包含wiremock:
androidTestImplementation "com.github.tomakehurst:wiremock-standalone:2.23.2"
使用gradle shadow插件,改用带阴影的jar:
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.github.jengelman.gradle.plugins:shadow:5.1.0'
}
}
apply plugin: com.github.jengelman.gradle.plugins.shadow.ShadowPlugin
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
android {
dependencies {
shadow "com.github.tomakehurst:wiremock-standalone:2.23.2"
androidTestImplementation files("$buildDir/libs/shadow.jar")
}
}
tasks.configureEach { theTask ->
def taskName = theTask.name.toString()
if (taskName =~ /generate.*Sources/) {
theTask.dependsOn tasks.named("shadowJar")
}
}
tasks.register("shadowJar", ShadowJar) {
baseName = 'shadow'
configurations = [project.configurations.shadow]
relocate ('javax.servlet', 'com.example.wiremockexample.javax.servlet'){}
}
完整的示例项目在此详细说明了此问题:https://github.com/libon/WiremockMeizuError
项目的PR可以实现以下答案:https://github.com/libon/WiremockMeizuError/pull/1
关于android - 在魅族设备上运行Wiremock Android测试时没有接口(interface)方法isAsyncStarted()错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56958824/