正如标题所述,我通过在JUnit 4测试中简单地调用构造函数而收到此错误。该测试位于我的应用程序的库模块内部。
在我的设置中,这足以引起问题:
import okhttp3.mockwebserver.MockWebServer
import org.junit.Test
class MyTest {
@Test
fun test() {
MockWebServer()
}
}
模块的 build.gradle
文件包含依赖项:
testImplementation("com.squareup.okhttp3:mockwebserver:4.0.1")
这是完整的堆栈跟踪:
java.lang.NoSuchFieldError: Companion
at okhttp3.internal.Util.<clinit>(Util.kt:69)
at okhttp3.mockwebserver.MockWebServer.<init>(MockWebServer.kt:176)
at com.redacted.MyTest.test(MyTest.kt:10)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
奇怪的是,如果我在app
模块中运行相同的测试,则在添加testImplementation
依赖项后,它会成功完成。
如果我将MockWebServer()
换成OkHttpClient.Builder()
,我也会得到类似的堆栈跟踪:
java.lang.NoSuchFieldError: Companion
at okhttp3.internal.Util.<clinit>(Util.kt:69)
at okhttp3.internal.connection.RealConnectionPool.<clinit>(RealConnectionPool.kt:261)
at okhttp3.ConnectionPool.<init>(ConnectionPool.kt:37)
at okhttp3.ConnectionPool.<init>(ConnectionPool.kt:39)
at okhttp3.OkHttpClient$Builder.<init>(OkHttpClient.kt:430)
我还尝试了更复杂的实例化方式(例如,通常在@Before
方法中,等等)。所有这些都导致相同的结果。