12

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

@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()));
    }
}

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

4

2 回答 2

7

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

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

于 2020-07-14T16:13:01.247 回答
3

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

Let's say you want to test MyActivity. First you need to define your ActivityTestRule as a not launch 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)

And then, launch your activity, after hilt injection:

@Before fun setup() {
    hiltRule.inject()
    testRule.launchActivity(Intent(targetContext, MyActivity::class.java))
}
于 2020-08-11T22:28:06.943 回答