我正在尝试使用MockRetrofit测试retrofit2应用程序接口。我有以下服务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)永远不会被调用。同步调用工作正常。知道为什么只有异步调用不起作用吗?
发布于 2017-09-14 00:26:30
问题是我没有等待后台线程调用回调方法。一旦我在调用enqueue之后放入一个Thread.sleep(1000),它就开始正常工作了。
https://stackoverflow.com/questions/46185731
复制相似问题