4

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

At the end of my method I want to assert if that toasts has been shown correctly to the user. Looking for how to do that I found this answer

But when you have a lot of tests running sequentially, you can't assume that the current toast has the text that you're expecting.

So I've developed an object called NotifiedToast that extends Toast class to get notified when the method .show() has been called and its text.

I'd like to know if this is the best way to perform this kind of test or if you guys know any way to do that trivially.

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;
}
Community
  • 1
  • 1
Lucas Santos
  • 150
  • 6

0 Answers0