【发布时间】: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