android - 无法在 Espresso 测试中获取 ApplicationContext

标签 android testing android-espresso

我在运行 Espresso 测试时不断收到以下错误:

尝试在空对象引用上调用虚方法“android.content.Context android.app.Instrumentation.getTargetContext()”

@RunWith(AndroidJUnit4.class)
public class TestLogin extends AndroidTestCase {

    @Rule
    public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule<>(MainActivity.class);

    @Test
    public void testVerifyCredentials() {
        Context context = this.getContext().getApplicationContext();
        SharedPreferences prefs = context.getSharedPreferences("current.user", Context.MODE_PRIVATE);
        assertTrue(prefs.getBoolean("IsLoggedIn", false));
    }
}

我已经将其作为 InstrumentationTestCase 进行了尝试,然后尝试改为执行 Context context = this.getInstrumentation().getTargetContext().getApplicationContext(); 但是仍然导致 NPE。

我做错了什么?

我在应用程序中使用的 SessionManager 类来管理 SharedPrefs:

包 com.nullpointexecutioners.buzzfilms.helpers;

导入android.content.Context; 导入 android.content.SharedPreferences;

导入 com.firebase.client.Firebase; 导入 com.nullpointexecutioners.buzzfilms.Major;

/**
 * Helper class for managing a session (i.e. persistence across launches of the app
 */
public class SessionManager {

    private static SessionManager sInstance;

    private final SharedPreferences pref;
    private final SharedPreferences.Editor editor;

    //SharedPref file name
    private static final String PREF_NAME = "current.user";

    //All Shared Preferences Keys
    private static final String IS_LOGIN = "IsLoggedIn";

    //Username
    public static final String KEY_USERNAME = "username";

    //Name
    public static final String KEY_NAME = "name";

    //Email
    public static final String KEY_EMAIL = "email";

    //Major
    public static final String KEY_MAJOR = "major";

    //is an Admin
    public static final String IS_ADMIN = "isAdmin";

    final Firebase mRef = new Firebase("redacted");

    /**
     * Constructor for instance of SessionManager
     * @param context of session
     * @return instance of SessionManager
     */
    public static SessionManager getInstance(Context context) {
        if (sInstance == null) {
            sInstance = new SessionManager(context);
        }
        return sInstance;
    }

    /**
     * Constructor for SessionManager class
     * @param context of session
     */
    private SessionManager(Context context) {
        pref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        editor = pref.edit();
    }

    /**
     * Create login session
     * @param username to store in SharedPrefs
     * @param name name of a user
     * @param email to store in SharedPrefs
     * @param major major of a user
     * @param isAdmin determines if a user is admin or not
     */
    public void createLoginSession(String username, String name, String email, String major, boolean isAdmin) {
        /*Store each value into SharedPrefs*/
        editor.putBoolean(IS_LOGIN, true);
        editor.putString(KEY_USERNAME, username);
        editor.putString(KEY_NAME, name);
        editor.putString(KEY_EMAIL, email);
        if (major.equals(Major.NONE.toString())) {
            editor.putString(KEY_MAJOR, "NONE");
        } else {
            editor.putString(KEY_MAJOR, major);
        }

        editor.putBoolean(IS_ADMIN, isAdmin);

        //Commit changes to SharedPrefs
        editor.apply();
    }

    /**
     * Update the current Session's values
     * @param name to update
     * @param email to update
     * @param major to update
     */
    public void updateSession(String name, String email, String major) {
        /*Store the updated values into SharedPrefs*/
        editor.putString(KEY_NAME, name);
        editor.putString(KEY_EMAIL, email);
        if (major.equals(Major.NONE.toString())) {
            editor.putString(KEY_MAJOR, "NONE");
        } else {
            editor.putString(KEY_MAJOR, major);
        }

        //Commit changes to SharedPrefs
        editor.apply();
    }

    /**
     * Checks if current user is logged in
     * If false, the user is redirected to WelcomeActivity to login or register
     * @return true or false depending if we're logged in
     */
    public boolean checkLogin() {
        return pref.getBoolean(IS_LOGIN, false);
    }

    /**
     * Checks if current user is an Admin
     * If false, the user won't have access to Admin functions
     * @return true or false depending if the user is an Admin
     */
    public boolean checkAdmin() {
        return pref.getBoolean(IS_ADMIN, false);
    }

    /**
     * Getter for currently logged in user's username
     * @return current user's username
     */
    public String getLoggedInUsername() {
        String username = null;
        if (pref.contains(KEY_USERNAME) && pref.getBoolean(IS_LOGIN, false)) {
            username = pref.getString(KEY_USERNAME, null);
        }
        return username;
    }

    /**
     * Getter for currently logged in user's name
     * @return current user's name
     */
    public String getLoggedInName() {
        String name = null;
        if (pref.contains(KEY_NAME) && pref.getBoolean(IS_LOGIN, false)) {
            name = pref.getString(KEY_NAME, "name");
        }
        return name;
    }

    /**
     * Getter for currently logged in user's email
     * @return current user's email
     */
    public String getLoggedInEmail() {
        String email = null;
        if (pref.contains(KEY_EMAIL) && pref.getBoolean(IS_LOGIN, false)) {
            email = pref.getString(KEY_EMAIL, null);
        }
        return email;
    }

    /**
     * Getter for currently logged in user's major
     * @return current user's major
     */
    public String getLoggedInMajor() {
        String major = null;
        if (pref.contains(KEY_MAJOR) && pref.getBoolean(IS_LOGIN, false)) {
            major = pref.getString(KEY_MAJOR, null);
        }
        return major;
    }

    /**
     * Clears session credentials
     */
    public void logoutUser() {
        //UnAuth from Firebase
        mRef.unauth();

        //Clear SharedPrefs and set IS_LOGIN to false
        editor.clear();
        editor.putBoolean(IS_LOGIN, false);
        editor.commit();
    }

    /**
     * Getter for accessing the current SharedPrefs
     * @return this session's SharedPrefs
     */
    public SharedPreferences getPref() {
        return pref;
    }
}

最佳答案

你试过吗?

InstrumentationRegistry.getInstrumentation().getTargetContext()

关于android - 无法在 Espresso 测试中获取 ApplicationContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36435037/

相关文章:

jquery - 使用 Jquery 测试字符串是否为 Integer

java - 由于 RenderScript,Android 仪器测试失败

android - Instrumented Test 中的 Internet 访问

java - fragment View 中 webview 的进度条

java - 有哪些方法可以测试依赖于静态方法的方法?

使用 Swagger/OAS 测试 API

android - 如何使用 Android Espresso 单击 RecyclerView 中的每个项目

android - Firebase UID 在多个应用程序中是否唯一?

android - 在此适配器中添加一个 AdView

Android - 从多点裁剪图像