2

I have a Custom Toast class -

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

I want to get the text in a Roboelectric test when this Toast is shown and assert it, for which I'm using this -

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

But that gives me a null pointer for R.id.text-

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

Is my way of accessing the custom Toast layout correct? Can there be a better way of asserting the custom Toast message ?

Gissipi_453
  • 1,250
  • 1
  • 25
  • 61
  • i don't want to make a custom toast. i want to unit test the custom toast that is already there – Gissipi_453 Dec 14 '20 at 07:16
  • how about a decent [mcve] and actually show the code of showedCustomToast(...) ? – Shark Dec 14 '20 at 09:41
  • showedCustomToast is a pre made function from Roboelectric. not my function. Again. Im using Roboelectric to test my code. Im not trying to show a toast, im trying to run unit tests in roboelectric test runner – Gissipi_453 Dec 14 '20 at 10:16

1 Answers1

1

You are using the wrong parameter sequence a

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

you should use ShadowToast.showedCustomToast(context,"Login failed. your credentials are not valid") and also you are passing R.id.text which integer value, not a context ...

Kamran Khadim
  • 161
  • 2
  • 7
  • I understand that but you are not passing the context to the function that is the error you should [check](https://stackoverflow.com/a/13689162/14588625) this – Kamran Khadim Dec 14 '20 at 10:24