Unit Test of Retrofit 2 api call with Mockito

后端 未结 2 1090
不思量自难忘°
不思量自难忘° 2021-01-12 11:18

I need some advices on how to mock a rest api. My application is in MVP architecture.

My interface for API:

public interface MyAPI {

    @GET(\"{cmd         


        
相关标签:
2条回答
  • 2021-01-12 11:39

    Thanks for @Ilya Tretyakov, I came out this solution:

    private ArgumentCaptor<Subscriber<Response>> subscriberArgumentCaptor;
    
    @Test
    public void testLoginWithCorrectUserNameAndPassword() throws Exception {
        mLoginPresenter.login("user@email.com","password");
        // create the mock Response object
        Response response = ......
    
        verify(service, times(1)).login(
            subscriberArgumentCaptor.capture(),
            stringUserNameCaptor.capture(),
            stringPasswordCaptor.capture()
        );
    
        subscriberArgumentCaptor.getValue().onNext(response);
        verify(view).loginSuccess();
    }
    
    0 讨论(0)
  • 2021-01-12 11:51

    You can do it in next way:

    @Test
    public void testLoginWithCorrectUserNameAndPassword() throws Exception {
        // create or mock response object
        when(service.login(anyString(), anyString(), anyString).thenReturn(Observable.just(response));
        mLoginPresenter.login("user@email.com","password");
        verify(view).loginSuccess();
    }
    
    @Test
    public void testLoginWithIncorrectUserNameAndPassword() throws Exception {
        // create or mock response object
        when(service.login(anyString(), anyString(), anyString).thenReturn(Observable.<Response>error(new IOException()));
        mLoginPresenter.login("user@email.com","password");
        verify(view).showError(anyString);
    }
    
    0 讨论(0)
提交回复
热议问题