Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
144 views
in Technique[技术] by (71.8m points)

java - How can I test the result of a button click that changes the Activity's view asynchronously?

I am trying to write some Activity tests for an app, and one particular scenario that I want to test is that when I click a certain button, the Activity view updates accordingly. However, clicking the button causes a somewhat long running asynchronous task to start and only after that task is completed does the view change.

How can I test this? I'm currently trying to use the ActivityInstrumentationTestCase2 class to accomplish this, but am having trouble figuring out how to have the test 'wait' until the asynchronous part of the button click task is complete and the view updates.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The most common and simplest solution is to use Thread.sleep():

public void testFoo() {
  TextView textView = (TextView) myActivity.findViewById(com.company.app.R.id.text);
  assertEquals("text should be empty", "", textView.getText());

  // simulate a button click, which start an AsyncTask and update TextView when done.
  final Button button = (Button) myActivity.findViewById(com.company.app.R.id.refresh);
  myActivity.runOnUiThread(new Runnable() {
    public void run() {
      button.performClick();
    }
  });

  // assume AsyncTask will be finished in 6 seconds.
  try {
    Thread.sleep(6000);
  } catch (InterruptedException e) {
    e.printStackTrace();
  }

  assertEquals("text should be refreshed", "refreshed", textView.getText());
}

Hope this helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...