'android unit test, how to test the activity crated by context.startActivity(intent)

Having an activity which has some functions need to be coverage tested.

    class HandlerActivity : AppCompatActivity() {
        override fun onCreate(savedInstanceState: Bundle ) {
            System.out.println("enter HandlerActivity.onCreate()")
            doSomething(intent)
        }
    }

//////////////
@RunWith(RobolectricTestRunner::class)
class HandlerActivityTest {
    @Test
    fun test_activity() {
     
        val conextSpy = spyk(ApplicationProvider.getApplicationContext())
        var testEx: Throwable? = null
            try {
                val intent = Intent(this, HandlerActivity::class.java)
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                conextSpy.startActivity(intent)
                Shadows.shadowOf(Looper.getMainLooper()).idle()
            } catch (ex: Throwable) {
                testEx = ex
            }
            junit.framework.Assert.assertNull(testEx)
            io.mockk.verify { contextSpy.startActivity(any()) }
       }
  

The test passed, but the HandlerActivity.onCreate() is not called.

How to unit test a onCreate() of an activity?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source