Mockito测试回调调用的



我想在mockito 中测试用户登录何时失败

我的接口

public interface OnLoginFinishListener {
  void onFail();
  void onSuccess();
}

我的LoginInterctor类

public class LoginInteractor {
  public void validateCredentialsAsync(final String email, final String password, final OnLoginFinishListener listener) {
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            if(email.equals("sample@email.com") && password.equals("123456")){
                listener.onSuccess();
            }else {
                listener.onFail();
            }
        }
    }, 5000);
  }
}

如何编写登录失败案例的测试,谢谢

您可能想要模拟您的OnLoginFinishListener并验证它是否调用了

            LoginInteractor in = new LoginInteractor();
            OnLoginFinishListener mockListner = mock(OnLoginFinishListener.class);
            doAnswer(new Answer<Void>() {
                @Override
                public Void answer(InvocationOnMock invocation) throws Throwable {
                    // TODO Auto-generated method stub
                    return null;
                }
            }).when(mockListner).onFail();
            doAnswer(new Answer<Void>() {
                @Override
                public Void answer(InvocationOnMock invocation) throws Throwable {
                    // TODO Auto-generated method stub
                    return null;
                }
            }).when(mockListner).onSuccess();
            in.validateCredentialsAsync("sample@email.com","wrong",mockListner);
            verify(mockListner,times(1)).onFail();
            verify(mockListner,never()).onSuccess();

相关内容

  • 没有找到相关文章

最新更新