微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用类App.getContextgetString的JUnit测试中的Java.lang.NullPointerException

如何解决使用类App.getContextgetString的JUnit测试中的Java.lang.NullPointerException

我正在尝试在我的类中测试处于静态上下文中的方法,我想在Junit类中对其进行测试,但是我得到了空指针异常。

我的App类别:

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!

解决方法

只需删除App类,因为将getString放在服务等逻辑代码中并不是很好。我只是向模型同事添加一个枚举,然后使用:holder.itemView.getContext().getString() 在我的适配器中出现开关状态。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。