How to run multiple Android tests stating toasts

I am trying to write a couple of validation tests for a simple login activity that shows some toasts to the user if something goes wrong, for example. "Invalid username", "Invalid username or password", etc.

At the end of my method, I want to claim that the toasts were correctly shown to the user. Looking for how to do this, I found this answer

But when you have many tests performed sequentially, you cannot assume that the current toast has the text that you expect.

So, I developed an object called NotifiedToast that extends the Toast class to receive a notification when the .show () method and its text are called.

I would like to know if this is the best way to perform such a test or if you guys know any way to do this is trivial.

LoginActivityTest.java

private boolean toastShown = false;
private String toastText = "";

@Rule
public ActivityTestRule<LoginActivity> mActivityTestRule = new ActivityTestRule<>(LoginActivity.class);

@Before
public void setUp() throws Exception
{
    toastShown = false;
    toastText = "";

    mActivityTestRule.getActivity().setToastListener(new SoftReference<NotifiedToastListener>(new NotifiedToastListener() 
    {
        @Override
        public void onToastShown(UUID toastId, String text)
        {
            toastShown = true;
            toastText = text;
        }
    }));
}

@Test
public void testPerformLoginWithBlankCredentials() throws Exception
{
    onView(withId(R.id.button_login)).perform(click());

    //Wait until the app performs the login into the server
    synchronized (syncObject)
    {
        while(!notified)
        {
            syncObject.wait(DEFAULT_WAITING_TIME);
        }
    }

    verify(toastText.equals(getInstrumentation().getTargetContext().getString(R.string.invalid_login_parameters)));
}

LoginActivity.java

private Reference<NotifiedToastListener> mToastListener;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
}

public void onLoginClick(View view)
{
    TextView textUsername = (TextView)findViewById(R.id.text_username);
    TextView textPassword = (TextView)findViewById(R.id.text_password);

    LoginManager loginManager = new LoginManager(LoginActivity.this);
    loginManager.addLoginListener(new WeakReference<LoginListener>(LoginActivity.this));
    loginManager.performLoginAsync(textUsername.getText().toString(), textPassword.getText().toString());
}

@Override
public void onLoginSuccess()
{

}

@Override
public void onLoginFailure(LoginException e)
{
    ToastUtils.showMessage(this, e.getFriendlyMessage(), Toast.LENGTH_LONG, mToastListener);
}

@VisibleForTesting
/*package*/ void setToastListener(Reference<NotifiedToastListener> listener)
{
    mToastListener = listener;
}
+4
source share

Source: https://habr.com/ru/post/1651439/


All Articles