Get context of test project in Android junit test case

后端 未结 10 2230
闹比i
闹比i 2020-12-02 12:58

Does anyone know how can you get the context of the Test project in Android junit test case (extends AndroidTestCase).

Note: The test is NOT instru

10条回答
  •  天涯浪人
    2020-12-02 13:16

    As you can read in the AndroidTestCase source code, the getTestContext() method is hidden.

    /**
     * @hide
     */
    public Context getTestContext() {
        return mTestContext;
    }
    

    You can bypass the @hide annotation using reflection.

    Just add the following method in your AndroidTestCase :

    /**
     * @return The {@link Context} of the test project.
     */
    private Context getTestContext()
    {
        try
        {
            Method getTestContext = ServiceTestCase.class.getMethod("getTestContext");
            return (Context) getTestContext.invoke(this);
        }
        catch (final Exception exception)
        {
            exception.printStackTrace();
            return null;
        }
    }
    

    Then call getTestContext() any time you want. :)

提交回复
热议问题