2017-05-01 58 views
0

我想寫一個單元測試,測試取消改造電話,但我卡住了。單元測試取消改造電話

這裏的實現:

public class LoginInteractorImpl extends AbstractInteractor implements LoginInteractor { 

    private volatile Call<ResponseBody> mCall; 

    private UserRepo mUserRepository; 

    @Inject 
    public LoginInteractorImpl(WorkerThread workerThread, MainThread mainThread, UserRepo userRepository) { 
     super(workerThread,mainThread); 
     this.mUserRepository = userRepository; 
    } 

    @Override 
    public void login(final String username, final String password, final OnLoginFinishedListener listener) { 
    mWorkerThread.execute(new Runnable() { 
      @Override 
      public void run() { 
       mCall = mUserRepository.doLogin(Credentials.basic(username, password)); 

       enqueue(new LoginCallbackImpl(mWorkerThread, mMainThread, listener)); 
      } 
     }); 

    } 

    @Override 
    public void cancel() { 
     if(mCall != null) { 
      mCall.cancel(); 
     } 
    } 

    void enqueue(LoginCallback callback){ 
     mCall.enqueue(callback); 
    } 
} 

下面是我在我的TestClass這麼遠:

public class LoginInteractorTest { 

    private LoginInteractorImpl mLoginInteractor; 

    @Mock 
    UserRepo mockUserRepository; 

    @Mock 
    private Call<ResponseBody> mockCall; 

    @Mock 
    private LoginInteractor.OnLoginFinishedListener mockLoginListener; 

    @Before 
    public void setUp() throws Exception { 

     MockitoAnnotations.initMocks(this); 

     mLoginInteractor = new LoginInteractorImpl(new FakeWorkerThread(), new FakeMainThread(), mockUserRepository); 
    } 

    ... 

    @Test 
    public void shouldCancelLoginCall() throws Exception { 

     final String username = "test"; 
     final String password = "testtest"; 

     LoginInteractorImpl spy = Mockito.spy(mLoginInteractor); 

     when(mockUserRepository.doLogin(anyString())) 
      .thenReturn(mockCall); 

     final CountDownLatch latch = new CountDownLatch(1); 

     // Somehow delay the call and cancel it instead? 

     when(mLoginInteractor.enqueue(any(LoginCallback.class))) 
      .thenAnswer(
       // Somehow pospone the call from executing 
      ); 

     // Enqueue logincall 
     mLoginInteractor.login(username, password, mockLoginListener); 

     // Cancel call 
     mLoginInteractor.cancel(); 

     // Verify that cancel was called 
     verify(mockCall, times(1)).cancel(); 
    } 
} 

我的問題是如何從正在執行停止mockCall並驗證我我成功地做了我的取消?我最好的選擇是我不得不使用CountDownLatch,但是我以前從未使用它,並且無法在任何地方查找和回答如何在我的用例中使用它。

回答

0

找到自己的答案:

public void shouldCancelLoginCall() throws Exception { 

    final String username = "test"; 
    final String password = "testtest"; 

    LoginInteractorImpl spy = Mockito.spy(mLoginInteractor); 

    when(mockUserRepository.doLogin(anyString())).thenReturn(mockCall); 

    doNothing().when(spy).enqueue(any(LoginCallback.class)); 

    mLoginInteractor.login(username, password, mockLoginListener); 

    mLoginInteractor.cancel(); 

    verify(mockCall, times(1)).cancel(); 
}