0

Can someone teach me how to test the sample code below?

How to I write espresso test for this? Since no view action is required?

public class SampleActivity extends AppCompatActivity {
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        Intent intent = new Intent(this, NextActivity.class);
        startActivity(intent);
    }
}

I would want to test whether the activity was actually started. Please help me. Thanks in advance.

Archie G. Quiñones
  • 11,638
  • 18
  • 65
  • 107

3 Answers3

2

This has been answered multiple times:

  1. From obtaining the activity at the time of test execution:

How can I check if the new activity was started

  1. To the usage of espresso-intents artifact (preferred option):

How to validate whether opened correct activity - Espresso

Keep in mind that the usage of IntentsTestRule might be problematic here, it used to call Intents.init() after your activity is launched, which will be too late as you will already be in the new activity. Not sure if this behavior is still in place, but you can work this around by calling init() manually in @Before method of your test class, don't forget to do Intents.release() in your teardown

Be_Negative
  • 4,892
  • 1
  • 30
  • 33
  • Thank you very much. For my specific question, I had to setup the Intent.init() at the `@BeforeClass` and `@AfterClass` (for teardown) for my test to pass. Thank you very much. :) – Archie G. Quiñones Feb 26 '18 at 06:08
0

Example with Intents.intending(should be before the launch):

@get:Rule
var mActivityTestRule = ActivityTestRule(LoginActivity::class.java, false, false)

@Before
fun before() {
    Intents.init()
}

@After
fun after() {
    Intents.release()
}

@Test
fun whenStartWithUser_shouldOpenHomeScreen() {
    val matcherIntent = hasComponent(HomeActivity::class.java.name)

    Intents.intending(matcherIntent).respondWith(Instrumentation.ActivityResult(Activity.RESULT_OK, null))
    mActivityTestRule.launchActivity(Intent())
    Intents.intended(matcherIntent)
}
JBarbosa
  • 134
  • 8
-2

Read the documentation about Log and Logcat. You can track all the actions taking place there.