使用Robolectric测试异步请求

时间:2019-01-07 21:31:58

标签: java android testing robolectric

我正在尝试使用robolectric测试异步请求的响应。

这是我的机器人考试班:

@RunWith(RobolectricTestRunner.class)
@Config(sdk = 18, application = Vision.class)

public class robolectricTest {

  Facade facade;
  private String username;
  private String password;
  ErrorListener errorListener = new ErrorListener();
  private TokenInfo response;


  @Before
  public void setup() throws Exception {
    username = "user1";
    password = "pass";
    facade = Vision.legacyComponent.provideFacade();
  }

  @Test
  public void authenticate() {
    System.out.println("outside");
    facade.authenticate(username, password, token -> {
      System.out.println("inside");
      assert token != null;
      return null;
    }, errorListener);
  }
}

问题是(我猜),因为这是一个异步请求,robolectric完成了测试,但是响应尚未返回。

所以我可以在控制台中看到测试打印outside,但从不打印inside,如果我添加Thread.sleep()

没关系

有没有办法让跑步者等待回应?

感谢您的每条建议/回复/帮助

最诚挚的问候

编辑:

我用Thread.sleep()Robolectric.getForegroundThreadScheduler().pause()投降了.unPause()

这仍然是一个非常丑陋的解决方法,因此,如果有人有更好的解决方案,请在此处分享。

0 个答案:

没有答案