打开VS,创建工程,然后添加 Appium-dotnet-driver.dll and WebDriver 引用 (此Demo用的是 C# code)
添加 如下命名空间引用:
using OpenQA.Selenium.Appium.Android; using OpenQA.Selenium.Appium; using OpenQA.Selenium.Remote; using OpenQA.Selenium;
初始化 android driver:
private static AndroidDriver<AppiumWebElement> Initialize(string package, string activity) { AndroidDriver<AppiumWebElement> driver = null; DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities.SetCapability("device", "Android"); //Android device capabilities.SetCapability(CapabilityType.Platform, "Windows"); capabilities.SetCapability("deviceName", "DeviceName"); //Device Name (we can get it using CMD: adb devices) capabilities.SetCapability("platformName", "Android"); capabilities.SetCapability("platformVersion", "21"); capabilities.SetCapability("appPackage", package); //App package value capabilities.SetCapability("appActivity", activity); //App activity value Uri uri = new Uri("http://127.0.0.1:4723/wd/hub/"); //open Appium, can get this value TimeSpan timeSpan = TimeSpan.FromSeconds(120); driver = new AndroidDriver<AppiumWebElement>(uri, capabilities, timeSpan); return driver; }
DeviceName -- 可以通过 adb devices 命令得到
package, 和 activity 是你要测试的 app的 package和activity, 打开你要测试的app,然后 打开 uiautomatorviewer.bat (在 Android SDK安装路径下的 tools文件夹下)uiautomatorviewer 可以得到 app的 元素 Id,className 等
初始化 android driver之后就可以写 test cases了。
以 模拟器中的 计算器 app为例:
static void Main(string[] args) { AndroidDriver<AppiumWebElement> driver = Initialize("com.android.calculator2", "com.android.calculator2.Calculator"); AppiumWebElement clear = driver.FindElement(By.ClassName("android.widget.Button")); clear.Click(); AppiumWebElement two = driver.FindElement(By.Name("5")); //click 5 two.Click(); AppiumWebElement plus = driver.FindElement(By.Id("plus")); //Click + plus.Click(); AppiumWebElement four = driver.FindElement(By.Name("9")); //Click 9 four.Click(); AppiumWebElement equalTo = driver.FindElement(By.Name("=")); //Click = equalTo.Click(); }
元素的 Name, Id, Classname 等可以通过 uiautomatorviewer.bat来找。
可以通过如下来截取图片
driver.GetScreenshot().SaveAsFile(pngFileName, ImageFormat.Png);