【问题标题】:How to test multiple activities using Android Espresso如何使用 Android Espresso 测试多个活动
【发布时间】:2018-07-16 14:23:22
【问题描述】:

假设有两个活动 A 和 B。A 是登录活动,其中包含用户名、密码字段和登录按钮。一旦输入用户名和密码并单击登录按钮,它就会进行网络调用。

如果我们要在同一活动中测试该视图的视图,它将起作用(如果不是,我们可以使用自定义 IdlingResource 并进行管理)。

我想在登录过程完成后测试 B 活动。但 B 活动也有一些网络调用(同时出现进度条)。所以直接onView() 断言失败了。有没有标准的方法来实现这一目标?可以通过在onView() 断言之前添加Thread.sleep() 语句来实现,我不想这样做。我该如何测试这个场景。

【问题讨论】:

  • 您使用哪种技术进行网络调用? Espresso 只能在使用 AsyncTask 类时检测并等待并行执行。
  • 我正在使用retrofit。所以我使用IdlingResource 让 Espresso 等到通话完成。它工作正常,没有问题。我想要的是让 Espresso 等待第二个活动的通话完成。

标签: android junit android-testing android-espresso


【解决方案1】:

如果您的第二个活动有操作完成的视觉标志,您可以使用此解决方案:

创建接口:

/**
* Interface for expectations of compliance with the conditions.
*/
public interface Condition {
 /**
  * @return text description for log output when check failed.
 */
 String getDescription();

 /**
  * @return true if the condition is met.
  */
 boolean check();
}

并像这样使用它:

/**
* Wait while condition come true or timeout limit.
*
* @param condition condition for exit
* @param timeout   limit in seconds
* @throws Exception exception
*/
public static void waitForCondition(Condition condition, int timeout) throws Exception {
final int CONDITION_NOT_MET = 0;
final int CONDITION_MET = 1;
final int TIMEOUT = 2;

final int INTERVAL = 250;

int status = CONDITION_NOT_MET;
int elapsedTime = 0;

do {
  if (condition.check()) {
    status = CONDITION_MET;
  } else {
    elapsedTime += INTERVAL;
    delay(INTERVAL);
  }

  if (elapsedTime >= timeout * 1000) {
    status = TIMEOUT;
    break;
  }
} while (status != CONDITION_MET);

if (status == TIMEOUT) {
  String msg = condition.getDescription() + " - took more than " + timeout + " seconds. Test stopped.";
  log(msg);
  throw new Exception(msg);
 }
}

例子:

public class MovieScreenVisible implements Condition {
  @Override
  public String getDescription() {
    return "Movie screen should be on the top";
  }

  @Override
  public boolean check() {
    Activity activity = TestBase.getCurrentActivity();
    if (activity == null || !(activity instanceof MovieActivity)) {
      return false;
    }

    ViewGroup layout = activity.findViewById(R.id.movie_fragment);
    return layout != null && layout.getVisibility() == View.VISIBLE;
  }
}

// wait maximum 30 seconds until movie screen should be visible
waitForCondition(new MovieScreenVisible(), 30); 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-28
    • 1970-01-01
    相关资源
    最近更新 更多