参考的网上资料,也看了《腾讯Android的自动化实战》,主要是uiautomator1.0。
公司网络可以直接加载androidx.test.uiautomator:uiautomator:2.2.0 ,那就直接从2.0开始了,(minSdkVersion 18)
在androidTest包目录下创建UiAutomatorDemo.java,测试打开酷狗App,跳过广告和注册,搜索指定歌曲。
import android.content.Context;
import android.content.Intent;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
import androidx.test.uiautomator.UiDevice;
import androidx.test.uiautomator.UiObject;
import androidx.test.uiautomator.UiObjectNotFoundException;
import androidx.test.uiautomator.UiSelector;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.IOException;
@RunWith(AndroidJUnit4.class)
public class UiAutomatorDemo {
public String PackageName="com.kugou.android";
public UiDevice uiDevice;
public Context context;
@Before//2.0基于instrument,所以获取设备,还是上下文环境
public void setUp(){
//获取设备,只用UiDevice.getInstance()是不行的,要用UiDevice.getInstance(instrument)
uiDevice=UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
//获取上下文,instrument.getContext
context= InstrumentationRegistry.getInstrumentation().getContext();
//获取Intent,只需要测试包名,这点不错
Intent intent=context.getPackageManager().getLaunchIntentForPackage(PackageName);
//启动App
context.startActivity(intent);
}
@Test
public void test_kugou() throws UiObjectNotFoundException {
//UiObject获取控件实例,UiSelector选择器
//点击广告页面右上角“跳过”//实测经常见不到广告,直接被第一时间点掉啦?
UiObject skip=new UiObject(new UiSelector().className("android.view.View").index(1));