Espresso 2.0
最近发布了Espresso 2.0,现在成为了Android Support Library的一部分。这个消息是在android dev博客上宣布的。
设置指南
同时他们还链接了一个更新的设置指南。你可以在那里找到从零开始配置或更新现有的espresso 2.0配置的说明。
其他提示
以上两个链接包含了所需的所有信息。如果不够,我列出了一些常见错误。
升级Android Studio至1.0.*
首先升级你的Android Studio构建版本。你应该能够从稳定版本渠道(=默认)得到至少1.0版本。所以只需使用菜单选项Android Studio > 检查更新...。
要获取最新的版本,你也可以进入偏好设置,搜索更新并将渠道更改为canary channel。
将Android Support Library更新至v11+
Espresso从11版本开始包含在Support library中,所以你必须获取至少该版本。使用Android SDK Manager检查更新。Support Library位于底部的Extras树中。
新依赖和命名空间
如果从旧版Espresso升级,你需要更新依赖和命名空间。对于新项目,只需将它们添加到build.gradle
文件中的dependencies
中即可。
dependencies {
androidTestCompile 'com.android.support.test.espresso:espresso-core:2.0'
androidTestCompile 'com.android.support.test:testing-support-lib:0.1'
}
由于命名空间发生了变化,您需要更新所有的导入:
android.support.test.espresso
请注意,使用静态导入更加容易。以下是
一些常用的导入示例:
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static android.support.test.espresso.matcher.ViewMatchers.withContentDescription;
对于断言,使用 Hamcrest,以下是一些例子:
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.anyOf;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.startsWith;
import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.equalToIgnoringCase;
import static org.hamcrest.Matchers.equalToIgnoringWhiteSpace;
测试执行器
测试执行器需要在build.gradle
文件中的defaultConfig和从Android Studio启动测试时使用的运行配置中进行配置。
defaultConfig {
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
在您的运行配置中,将以下内容用作检测运行器(仅使用完整类名):
android.support.test.runner.AndroidJUnitRunner
示例测试用例
最后一个示例测试用例。请注意,MainActivity
是您想要测试的活动。测试本身是以 test 开头的公共方法,例如下面示例中的 testListGoesOverTheFold
。
@LargeTest
public class HelloWorldEspressoTest extends ActivityInstrumentationTestCase2<MainActivity> {
public HelloWorldEspressoTest() {
super(MainActivity.class);
}
@Override
public void setUp() throws Exception {
super.setUp();
getActivity();
}
public void testListGoesOverTheFold() {
onView(withText("Hello world")).check(isDisplayed());
}
}
了解有关编写测试的更多信息,请访问Espresso入门指南。