Android UI测试用WireMockRule遇NoClassDefFoundError如何解决?
java.lang.NoClassDefFoundError for HttpRequestExecutor in WireMock + Android Espresso Tests Hey, let's tackle that frustrating error you're seeing when initializing WireMockRule. The root issue is that WireMock needs the org.apache.http.protocol.HttpRequestExecutor class, which isn't being properly resolved in your Android test environment. Here are a few proven solutions to get your tests running again:
Solution 1: Explicitly Add Apache HttpCore Dependency
The HttpRequestExecutor class lives in the Apache HttpCore library, not just HttpClient. Even though httpclient-android depends on HttpCore, Android's test classloader sometimes doesn't pick up transitive dependencies correctly. Add this line to your module-level build.gradle:
androidTestImplementation "org.apache.httpcomponents:httpcore:4.4.14"
Keep your existing WireMock and httpclient-android config, so your final test dependencies will look like this:
androidTestImplementation 'androidx.test:rules:1.1.0' androidTestImplementation("com.github.tomakehurst:wiremock:2.18.0") { exclude group: 'org.apache.httpcomponents', module: 'httpclient' exclude group: 'asm', module: 'asm' exclude group: 'org.json', module: 'json' exclude group: 'com.google.guava', module:'guava' } androidTestImplementation("org.apache.httpcomponents:httpclient-android:4.3.5.1") androidTestImplementation("org.apache.httpcomponents:httpcore:4.4.14")
Solution 2: Upgrade WireMock to a Newer, Android-Friendly Version
WireMock 2.18.0 is pretty old (released in 2018), and newer versions have better handling for Android's missing Apache HttpClient libraries. Try upgrading to version 2.27.2 (a stable, well-supported release):
androidTestImplementation("com.github.tomakehurst:wiremock:2.27.2") { exclude group: 'org.apache.httpcomponents', module: 'httpclient' exclude group: 'com.google.guava', module:'guava' exclude group: 'org.json', module: 'json' } androidTestImplementation("org.apache.httpcomponents:httpclient-android:4.3.5.1")
This version often resolves classloading issues without needing to add HttpCore explicitly.
Solution 3: Use an Android-Optimized WireMock Variant
If you want to avoid dealing with Apache HttpClient dependencies entirely, try using a community-maintained WireMock build made specifically for Android:
androidTestImplementation "com.github.haroldadmin:wiremock-android:0.1.9"
This library handles all the Android-specific dependency tweaks under the hood, so you can initialize WireMockRule without extra configuration.
Why This Happens
Android removed the built-in Apache HttpClient library starting with API 23, so we have to use httpclient-android as a replacement. Your error occurs because WireMock's HttpClientFactory relies on HttpRequestExecutor from Apache HttpCore, which wasn't being included in your test classpath (either due to transitive dependency issues or old WireMock behavior).
内容的提问来源于stack exchange,提问作者Toan Tran Van

