【问题标题】:Not able to test Async Retrofit2 API calls using MockRetrofit无法使用 MockRetrofit 测试 Async Retrofit2 API 调用
【发布时间】:2017-09-12 21:39:53
【问题描述】:

我正在尝试使用 MockRetrofit 测试 Retrofit2 API。 我有以下服务 API:

  interface AuthApi
  {
      public Call<Result> signin( String username, String pswd );
  }

Mock 实现如下所示:

    public class MockAuthService implements AuthApi
    {
         BehaviorDelegate<AuthService> delegate;
         public MockAuthService( BehaviorDelegate<AuthService> d )
         {
             delegate = d;
         } 

         public Call<Result> signin( String username, String pswd )
         {
             return delegate.returningResponse( new Result() ).signin( usernam, pswd );

         }
    }

我的测试如下:

@Test
public void testSuccessfulLogin()
{
    // Create MockRetrofit object

    MockAuthService service = new MockAuthService( mockRetrofit.create(AuthService.class) );
    Call<Result> call = service.signin("user", "pswd" );
    call.execute(); //This works fine. I get the result obj and check status code and stuff
    call.enqueue(new Callback<Result>()  // This does not work
    {
        @Override
        public void onResponse( Call<Result> call, Response<SignInResult.Result> response )
        {
            System.out.println( "onResponse" ); // This is never called
        }

        @Override
        public void onFailure( Call<Result> call, Throwable throwable )
        {
            System.out.println( "onFailure" ); // this is never called
        }
    } );
}

单元测试的异步部分(call.enqueue())不起作用。回调(onResponse 或 onFailure)永远不会被调用。 同步调用工作正常。 为什么只有异步调用不起作用的任何想法。

【问题讨论】:

  • 问题是我没有等待后台线程调用回调方法。一旦我在调用 enqueue 后放置了一个 Thread.sleep(1000) ,它就开始正常工作了。
  • 是的,我的问题还是一样,如何解决?

标签: android unit-testing retrofit2


【解决方案1】:

问题是我没有等待后台线程调用回调方法。一旦我在调用 enqueue 后放置了一个 Thread.sleep(1000) ,它就开始正常工作了。

【讨论】:

    猜你喜欢
    • 2017-08-09
    • 2016-06-03
    • 2021-05-20
    • 2020-04-28
    • 2021-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多