ComponentActivity ClassNotFoundException 尝试设置 Instrumented 测试时,使用 Android Compose 和 Hilt

ComponentActivity ClassNotFoundException when trying to setup Instrumented tests, with Android Compose and Hilt

我正在设置我的第一个仪器化单元测试并在 logcat 中遇到一个模糊的崩溃。

当应用程序尝试打开并且单元测试甚至没有 运行 因为应用程序未处于正确状态时,模拟器启动并立即崩溃。

2022-02-09 19:30:37.116 25764-25764/com.anotherday.day17.test E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.anotherday.day17.test, PID: 25764
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.anotherday.day17.test/androidx.activity.ComponentActivity}: java.lang.ClassNotFoundException: Didn't find class "androidx.activity.ComponentActivity" on path: DexPathList[[zip file "/data/app/~~NodQZs7v97-vYTPte3T7UQ==/com.anotherday.day17.test-25XuwB3vTwyNbSX-nlETDQ==/base.apk"],

它似乎在寻找 androidx.activity.ComponentActivity ,它在以下 gradle 依赖项中定义:

implementation 'androidx.activity:activity-compose:1.3.1'

不知道该去哪里找,这是我在 git 中的第一个测试和项目: https://github.com/davida5/ComposeNotepad/blob/main/app/src/androidTest/java/com/anotherday/day17/navigation/NavigatorTest.kt

将以下内容添加到您的AndroidManifest.xml

<manifest>
  <application>
    ...
    <activity android:name="androidx.activity.ComponentActivity" />
    ...
  <application>
<manifest>

如果您有调试变体的特定清单文件,请将其添加到该文件中,因为发布变体不需要此更改。

我终于想通了问题,需要实例化这样的撰写规则:

val composeRule = createAndroidComposeRule<MainActivity>()

而不是

val composeRule = createComposeRule()

第一个(正确的)调用允许传入带注释的 Hilt (@AndroidEntryPoint) Activity,而不是默认的 ComponentActivity,后者未带注释,因为它属于框架。这就是为什么它一直抱怨 ComponentActivity,如果你查看 createComposeRule() 的内部,就是它所做的一切,调用 createAndroidComposeRule()。