【问题标题】:Android Roboelectric test: null pointer in getting view id in Custom ToastAndroid Robolectric 测试:在自定义 Toast 中获取视图 ID 时的空指针
【发布时间】:2020-12-11 13:26:55
【问题描述】:

我有一个自定义 Toast 类 -

public static void makeToast(final Context context, String message) {

        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        final View layout = inflater.inflate(R.layout.toast_with_icon, null, false);

        TextView text = layout.findViewById(R.id.text);
        text.setText(message);
        text.setTextColor(Color.RED);

        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                Toast toast = new Toast(context.getApplicationContext());
                toast.setView(layout);
                toast.show();
            }
        });
    }

我想在显示此 Toast 时在 Roboelectric 测试中获取文本并声明它,为此我正在使用它 -

var checkMessage = ShadowToast.showedCustomToast("Login failed. your credentials are not valid", R.id.text)
assert(checkMessage)

但这给了我一个指向R.id.text的空指针-

java.lang.NullPointerException 在 org.robolectric.shadows.ShadowToast.showedCustomToast(ShadowToast.java:159) 在 in.novopay.novoloan.ui.login.data.LoginRepositoryTest.testLoginWithWrongCredentials(LoginRepositoryTest.kt:56)

我访问自定义 Toast 布局的方式是否正确? 有没有更好的方法来声明自定义 Toast 消息?

【问题讨论】:

  • 我不想制作自定义吐司。我想对已经存在的自定义 toast 进行单元测试
  • 一个像样的minimal reproducible example 怎么样,并实际显示showCustomToast(...) 的代码?
  • showedCustomToast 是 Roboelectric 的预制功能。不是我的职责。再次。我使用 Roboelectric 来测试我的代码。我不是想祝酒,我想在机器人电动测试运行器中运行单元测试

标签: android robolectric android-toast


【解决方案1】:

你使用了错误的参数序列a

ShadowToast.showedCustomToast("Login failed. your credentialsare not valid", R.id.text)

你应该使用 ShadowToast.showedCustomToast(context,"Login failed. your credentials are not valid") 而且您传递R.id.text 哪个整数值,而不是context ...

【讨论】:

  • 我明白,但你没有将上下文传递给函数,这是你应该checkthis
猜你喜欢
  • 2013-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-07
  • 1970-01-01
  • 2011-06-22
  • 1970-01-01
相关资源
最近更新 更多