如何使用Android Espresso

时间:2016-06-17 05:59:52

标签: android junit android-testing android-espresso

假设有两个活动A和B. A是登录活动,其中包含用户名,密码字段和登录按钮。输入用户名和密码并单击登录按钮后,它将进行网络呼叫。

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

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

1 个答案:

答案 0 :(得分:0)

如果您的第二个活动已经完成了直观的操作标志,则可以使用以下解决方案:

创建界面:

/**
* 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); 
相关问题