我正在尝试使用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)。 同步调用工作正常。 任何想法,为什么只有异步调用不起作用。
答案 0 :(得分:0)
问题是我没有等待后台线程调用回调方法。一旦我在调用enqueue之后放入Thread.sleep(1000)它就开始正常工作了。