Java.lang.NullPointerException 在 JUnit 测试中使用 class App.getContext().getString

Java.lang.NullPointerException in JUnit test with class App.getContext().getString

我正在尝试在我的 class 中测试静态上下文中的方法,我想在 Junit class 中测试它,但我遇到了空指针异常。

我的应用程序 class :

public class App extends MultiDexApplication {
    private static Context mContext;
    
    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this;
    }
    
    public static Context getContext() {
        return mContext;
    }
}

我的方法:

public class ColleagueChoice {
    static ColleagueApiService apiService = DI.getColleagueApiService();
    static List<Colleague> colleagueList = apiService.getColleagues();
    static String isEatingAt = App.getContext().getResources().getString(R.string.is_eating_at);
    static String isJoining = App.getContext().getResources().getString(R.string.is_joining);
    static String notDecided = App.getContext().getString(R.string.has_not_decided_yet);

    public static List<Colleague> setScarlettAndHughChoice() {
        Colleague scarlett = colleagueList.get(0);
        Colleague hugh = colleagueList.get(1);
        scarlett.setColleagueIsJoining(isJoining);
        hugh.setColleagueIsJoining(isJoining);
        List<Colleague> colleagueChoiceList = new ArrayList<>();
        colleagueChoiceList.add(scarlett);
        colleagueChoiceList.add(hugh);

        return colleagueChoiceList;
}

所以我在第 :

行收到此错误
static String isEatingAt = App.getContext().getResources().getString(R.string.is_eating_at);

UP!

干脆把Appclass去掉,因为把getString放在服务这样的逻辑代码里不太好。我只是向我的模型同事添加一个枚举,然后使用:holder.itemView.getContext().getString() 在我的带有开关条件的适配器中。