Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Espresso intended(hasComponent(...)) not working in simple example

There are many issues like this posted without anwers, I also have this problem with a new blank project, any idea what the problem is? Im not doing more than this:

public class ExampleInstrumentedTest {

@Test
public void useAppContext() {
    Intents.init();
    final Intent intent = new Intent(ApplicationProvider.getApplicationContext(), MainActivity.class);
    try (ActivityScenario<MainActivity> scenario = ActivityScenario.launch(intent)) {
        Log.d("++", "state: " + scenario.getState());
        assertTrue(scenario.getState() == Lifecycle.State.RESUMED);
        intended(hasComponent(MainActivity.class.getName()));
        Intents.release();
    }
}

}

It doesn't matter if I call Intents.init(); in setUp() or use IntentsTestRule or ActivityScenarioRule, the same issue occurs each time:

E/TestRunner: androidx.test.espresso.base.DefaultFailureHandler$AssertionFailedWithCauseError: Wanted to match 1 intents. Actually matched 0 intents.

Github repo

like image 274
David Avatar asked Oct 18 '25 19:10

David


1 Answers

Your test fails because an intent with the MainActivity component name is not launched by the application under test. The documentation states for intended():

Asserts that the given matcher matches a specified number of intents sent by the application under test.

So since your application under test is using MainActivity as its launcher intent, another intent with MainActivity as its component will not be fired by MainActivity.

A working (and more realistic) example is the following:

  • Verify that MainActivity successfully fires an Intent to launch OtherActivity.
// In MainActivity

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val otherActivity = Intent(this, OtherActivity::class.java)
    startActivity(otherActivity)
}

// In your instrumented test

@Test
fun otherActivityIsLaunchedByMainActivity() {
    Intents.init()

    val intent = Intent(ApplicationProvider.getApplicationContext<Context>(), MainActivity::class.java)
    val scenario = ActivityScenario.launch<MainActivity>(intent)
    intended(hasComponent(OtherActivity::class.java.name))

    Intents.release()
}
like image 77
gosr Avatar answered Oct 21 '25 08:10

gosr