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

前端 未结 2 1898
伪装坚强ぢ
伪装坚强ぢ 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.

提交回复
热议问题