用于 UI 测试的 Hilt 依赖注入说 "HiltAndroidRule" 没有被添加,但是它被添加了

Hilt dependency injection for UI testing says "HiltAndroidRule" wasn't added but it was

我正在尝试使用 Hilt 进行依赖项注入,但它给出了错误 java.lang.IllegalStateException: The component was not created. Check that you have added the HiltAndroidRule. 虽然添加了 HiltAndroidRule:

@RunWith(AndroidJUnit4.class)
@UninstallModules(ItemsModule.class)
@HiltAndroidTest
public class SelectItemActivityTest {

    @Rule
    public HiltAndroidRule hiltRule = new HiltAndroidRule(this);

    @Before
    public void init() {
        hiltRule.inject();
    }
    @BindValue
    List<Item> items = getItems();
    List<Item> getItems()  {
        List<Item> items = new ArrayList<>();
        items.add(new Item(1, "Item1", "", true, true, true));;
        items.add(new Item(2, "Item2", "", true, true, true));;
        items.add(new Item(3, "Item3", "", true, true, true));;
        return items;
    }

    @Rule
    public ActivityTestRule<SelectItemActivity> mActivityRule =
            new ActivityTestRule<>(SelectItemActivity.class);

    @Test
    public void text_isDisplayed() {
        onView(withText("Item1")).check(matches(isDisplayed()));
    }
}

我也尝试在 class 中添加一个 ItemsModule,但结果相同。

您必须使用 RuleChain 或将 order 参数应用于 Rule 注释来包装它。

这里有详细解释:https://developer.android.com/training/dependency-injection/hilt-testing#multiple-testrules

我在尝试测试不是启动器的 activity 时遇到了同样的错误。我正在使用 Kotlin,但非常相似的东西应该适用于 Java.

假设您要测试 MyActivity。首先,您需要将 ActivityTestRule 定义为未启动 activity:

val targetContext: Context = InstrumentationRegistry.getInstrumentation().targetContext

@get:Rule(order = 0) 
var hiltRule = HiltAndroidRule(this)

@get:Rule(order = 1) 
var testRule = ActivityTestRule(MyActivity::class.java, false, false)

然后,在注入刀柄后启动您的 activity:

@Before fun setup() {
    hiltRule.inject()
    testRule.launchActivity(Intent(targetContext, MyActivity::class.java))
}