How to register broadcast receiver inside instrumentation?

后端 未结 2 615
攒了一身酷
攒了一身酷 2021-01-23 09:33

I am trying to get bluetooth discovery results through an apk which runs as android junit runner. Everything works fine but while registerReciever I get below error. What could

相关标签:
2条回答
  • 2021-01-23 10:15

    I have found answer myself. Using InstrumentationRegistry.getTargetContext() solved my problem.

    InstrumentationRegistry.getInstrumentation(), returns the Instrumentation currently running.

    InstrumentationRegistry.getContext(), returns the Context of this Instrumentation’s package.

    InstrumentationRegistry.getTargetContext(), returns the application Context of the target application.

    Here are some info- https://developer.android.com/reference/android/support/test/InstrumentationRegistry.html#getTargetContext()

    But still I am not sure when to use InstrumentationRegistry.getContext()...

    0 讨论(0)
  • 2021-01-23 10:34

    InstrumentationRegistry.getTargetContext() returns the Context of the application under test.

    InstrumentationRegistry.getContext() returns the Context of the Instrumentation running the tests.

    Then, if you want to register a receiver as in the case you described you need you application Context. However, this is not really testing your application receives the broadcast as the receiver is not part of your it.

    Anyway, and answering your second question, the reason to use InstrumentationRegistry.getContext() is when your tests need access to resources or files that are not part of the application but only used in tests.

    EDIT

    Here there's an example. Two files, one in the app the other in tests

    src/androidTest/assets/sometestfile
    src/main/assets/someappfile
    

    then you can access them depending on the context

    @Test
    public final void testAccessToAppAssetsFromTest() throws IOException {
        final AssetManager assetManager = mInstrumentation.getTargetContext().getAssets();
        assetManager.open("someappfile");
    }
    
    @Test
    public final void testAccessToTestAssetsFromTest() throws IOException {
        final AssetManager assetManager = mInstrumentation.getContext().getAssets();
        assetManager.open("sometestfile");
    }
    

    If you try the opposite the test will fail.

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