我对回答自己的赏金问题感到有点尴尬,但这是...
我对此进行了严格的搜索,无法相信任何地方都没有发布答案。我已经很近了。我现在肯定可以运行跨活动的测试,但是我的实现似乎存在一些计时问题,这些问题并不总是能够可靠地通过。这是我所知道的唯一成功地跨多个活动进行测试的示例。希望我的提取和匿名化不会引入错误。这是一种简化测试,其中我在登录活动中键入用户名和密码,然后观察到在不同的“欢迎”活动中显示了正确的欢迎消息:
package com.mycompany;
import android.app.*;
import android.content.*;
import android.test.*;
import android.test.suitebuilder.annotation.*;
import android.util.*;
import android.view.*;
import android.widget.*;
import static org.hamcrest.core.Is.*;
import static org.hamcrest.core.IsNull.*;
import static org.hamcrest.core.IsInstanceOf.instanceOf;
import static org.junit.Assert.*;
import static com.mycompany.R.id.*;
public class LoginTests extends InstrumentationTestCase {
@MediumTest
public void testAValidUserCanLogIn() {
Instrumentation instrumentation = getInstrumentation();
Instrumentation.ActivityMonitor monitor = instrumentation.addMonitor(AuthenticateActivity.class.getName(), null, false);
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setClassName(instrumentation.getTargetContext(), AuthenticateActivity.class.getName());
instrumentation.startActivitySync(intent);
Activity currentActivity = getInstrumentation().waitForMonitorWithTimeout(monitor, 5);
assertThat(currentActivity, is(notNullValue()));
View currentView = currentActivity.findViewById(username_field);
assertThat(currentView, is(notNullValue()));
assertThat(currentView, instanceOf(EditText.class));
TouchUtils.clickView(this, currentView);
instrumentation.sendStringSync("MyUsername");
currentView = currentActivity.findViewById(password_field);
assertThat(currentView, is(notNullValue()));
assertThat(currentView, instanceOf(EditText.class));
TouchUtils.clickView(this, currentView);
instrumentation.sendStringSync("MyPassword");
instrumentation.removeMonitor(monitor);
monitor = instrumentation.addMonitor(WelcomeActivity.class.getName(), null, false);
currentView = currentActivity.findViewById(login_button;
assertThat(currentView, is(notNullValue()));
assertThat(currentView, instanceOf(Button.class));
TouchUtils.clickView(this, currentView);
currentActivity = getInstrumentation().waitForMonitorWithTimeout(monitor, 5);
assertThat(currentActivity, is(notNullValue()));
currentView = currentActivity.findViewById(welcome_message);
assertThat(currentView, is(notNullValue()));
assertThat(currentView, instanceOf(TextView.class));
assertThat(((TextView)currentView).getText().toString(), is("Welcome, MyUsername!"));
}
}
这段代码显然不是很可读。实际上,我已经使用类似于英语的API将其提取到一个简单的库中,所以我可以这样说:
type("myUsername").intoThe(username_field);
click(login_button);
我已经对大约4项活动进行了深入测试,并且对这种方法行得通的情况感到满意,尽管正如我所说,似乎偶尔会出现计时问题,但我并未完全弄清楚。我仍然对听到跨活动进行测试的任何其他方式感兴趣。