如何在Android断言祝酒词上执行多项测试

时间:2016-08-16 17:24:02

标签: java android automated-tests android-espresso

我正在尝试为一个简单的登录活动编写一些检测测试,如果出现问题,可以向用户显示一些问题,例如: "用户名无效","用户名或密码错误"等。

在我的方法结束时,我想断言是否已向用户正确显示了toasts。正在寻找如何做到这一点,我找到了answer

但是当你按顺序运行大量测试时,你不能假设当前的吐司有你期待的文本。

所以我开发了一个名为NotifiedToast的对象,它扩展了Toast类,以便在调用方法.show()及其文本时得到通知。

我想知道这是否是进行此类测试的最佳方式,或者您是否知道如何做到这一点。

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

0 个答案:

没有答案