Espresso 学习
针对源码测试
针对源码的测试,其实在google 的官方网站 Espresso 介绍就有,此外,还可以在Espresso guide上看到更详细的介绍和 demo。这里就简单提及几点:
1.配置 build.gradle
defaultConfig {
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
} dependencies {
androidTestCompile 'com.android.support:support-annotations:23.0.1'
androidTestCompile 'com.android.support.test:runner:0.4.1'
androidTestCompile 'com.android.support.test:rules:0.4.1'
// Optional -- UI testing with Espresso
androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.1'
}
2.同步 project(修改完 build.gradle 后,android studio 会自动提示你 Sync project)
3.编写代码 (同步完后,src 下会多一个 androidTest 文件夹,在该目录下编写测试代码)
4.附录测试代码一份,如下:
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
...
@RunWith(AndroidJUnit4.class)
@LargeTest
public class ChangeTextBehaviorTest {
private String mStringToBetyped;
//配置ActivityTestRule,这里用来指定启动哪个Activity,这里的传入Activity的class属性
@Rule
public ActivityTestRule mActivityRule = new ActivityTestRule<>(
MainActivity.class);
@Before
public void initValidString() {
// Specify a valid string.
mStringToBetyped = "Espresso";
}
@Test
public void changeText_sameActivity() {
// Type text and then press the button.
onView(withId(R.id.editTextUserInput))
.perform(typeText(mStringToBetyped), closeSoftKeyboard());
onView(withId(R.id.changeTextBt)).perform(click());
// Check that the text was changed.
onView(withId(R.id.textToBeChanged))
.check(matches(withText(mStringToBetyped)));
}
}
5.点击 run 按钮,即可运行指定的 test
只有 APK
Espresso 也是基于 Instrumentation 实现的,所以可以基于这个思路尝试用 robotium 的方式来解决 (注意:被测 APK 要与测试工程同一签名)
参考资料
1.在 android studio 新建一个包名跟待测 APK 一样的 android 工程
2.build.gralde 配置跟上述一样
3.编写代码模块,要做一些修改
通过 java 反射获取到指定 Activity 的 class,然后将反射获取的对象传给 ActivityTestRule,构造 ActivityTestRule 对象,代码如下:
private static final String CLASSNAME = "com.jieshun.jslife.activity.main.MainActivity";
private static Class extends Activity> activityClass;
static {
try {
activityClass = (Class extends Activity>) Class.forName(CLASSNAME);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
@Rule
public ActivityTestRule> mActivityRule = new ActivityTestRule<>(
activityClass);
借助 Context 类,获取指定 id 的具体数值,代码如下:
private int getId(String id){
Context targetContext = InstrumentationRegistry.getTargetContext();
String packageName = targetContext.getPackageName();
return targetContext.getResources().getIdentifier(id,"id",packageName);
}
4.执行时,只通过 android studio 或 gradle 编译出 APK,不能直接通过 android studio 直接安装 (因为同包名,AS 会问你是否卸载已存在手机里的待测 APP)
5.借助指令来安装,通过shell adb install -r path\app-debug-androidTest-unaligned.apk来安装
6.借助指令来测试,通过shell adb shell am instrument -w 待测包名.test/android.support.test.runner.AndroidJUnitRunner来执行测试,也可以加上-e 来指定执行某个测试方法。具体详解可以看命令行执行测试
周末的一点学习,仅供参考