Search code examples
androidjunit4

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


I'm trying to test a method that is in a static context in my class and I want to test it in Junit class but I got a null pointer exception.

My App class :

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

My Method :

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;
}

So I'm getting this error at line :

static String isEatingAt = App.getContext().getResources().getString(R.string.is_eating_at);

UP!


Solution

  • Simply remove the App class because this is not very good to put getString in a logic code like services. I just add an enum to my model Colleague and then use: holder.itemView.getContext().getString() in my adapter with a switch condition.