Android Espresso Intents test randomly fail with ``init() must be called prior to using this method``

前端 未结 2 1875
伪装坚强ぢ
伪装坚强ぢ 2020-12-28 18:03

I am working on pushing a project into espresso testing currently. I have read a bunch of documents and follow the given practises to get started.

Everything works f

相关标签:
2条回答
  • 2020-12-28 18:30

    Two Solutions:

    1. Use ActivityTestRule instead of IntentsTestRule and then in your @Before and @After manually call Intents.init() and Intents.release() respectively.
    2. Write a custom IntentTestRule and override beforeActivityLaunched() to include your AccountManager logic. Use afterActivityFinished for your current @After logic. This will also allow you to just use the default IntentTestRule constructor. (Preferred Solution)

    As to why this is happening:

    "Finally on an unrelated note, be careful when using the new IntentsTestRule. It does not initialize, Intents.init(), until after the activity is launched (afterActivityLaunched())." - Shameless plug to my own post (halfway down helpful visual)

    I think you are running into a race condition where in your @Before method you are executing launchActivity() then espresso tries to execute intending(not(isInternal())).respondWith(new Instrumentation.ActivityResult(Activity.RESULT_OK, null)); before your activity is actually created, which means afterActivityLaunched() isn't called, which means neither is Intents.init(), crash!

    Hope this helps.

    0 讨论(0)
  • 2020-12-28 18:30

    IntentsTestRule is derived from ActivityTestRule and should manage Intents.init() and Intents.release() for you.

    However, in my case the IntentsTestRule did not work properly. So I switch back to ActivityTestRule and call Intents.init() before and Intents.release() after the test which sent the Intent.

    For more information please see this reference.

    0 讨论(0)
提交回复
热议问题