TestNG Annotations import org.testng.annotations.Test; import org.testng.annotations.BeforeClass; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeSuite; import org.testng.annotations.AfterSuite; import org.testng.annotations.BeforeTest; import org.testng.annotations.AfterTest; @Test: Denotes a test method. @BeforeClass: Runs once before the first test method in the current class. @AfterClass: Runs once after all the test methods in the current class. @BeforeMethod: Runs before each test method. @AfterMethod: Runs after each test method. @BeforeSuite: Runs once before all tests in the suite. @AfterSuite: Runs once after all tests in the suite. @BeforeTest: Runs once before all tests within the currenttag. @AfterTest: Runs once after all tests within the current tag. TestNG Assertions: import org.testng.Assert; Assert.assertEquals(actual, expected); Assert.assertTrue(condition); Assert.assertFalse(condition); Assert.assertNull(object); Assert.assertNotNull(object); TestNG Parameters: import org.testng.annotations.Parameters; import org.testng.annotations.Optional; @Parameters({ "parameterName" }) @Test public void testMethod(@Optional("defaultValue") String parameterValue) { // Test method implementation } TestNG Data Providers: import org.testng.annotations.DataProvider; @DataProvider(name = "dataProviderName") public Object[][] dataProviderMethod() { // Return test data as a 2D array return new Object[][] { { data1 }, { data2 }, ... }; } @Test(dataProvider = "dataProviderName") public void testMethod(Object data) { // Test method implementation } TestNG Groups: @Test(groups = "groupName") public void testMethod() { // Test method implementation } TestNG Dependencies: @Test(dependsOnMethods = "methodName") public void testMethod() { // Test method implementation }
TestNG Basics
Appium Commands
Appium Commands Installing Appium Install Appium 2.0 > npm install -g appium@next Appium Doctor Install Appium Doctor > npm install -g @appium/doctor Check Android Setup > appium-doctor --android Check iOS Setup > appium-doctor --ios Appium Drivers List Appium Drivers > appium driver list Install Driver > appium driver install uiautomator2 Upgrade Driver > appium driver update uiautomator2 Uninstall Driver > appium driver uninstall uiautomator2 Appium Plugins List Appium Plugins > appium plugin list Install Plugin > appium plugin install relaxed-caps Upgrade Plugin > appium plugin update appium-dashboard Uninstall Plugin > appium plugin uninstall relaxed-caps Appium Server Start Appium Server > appium server [list-of-options] Appium Server Parameters (Optional) --address: IP address where you want to run your tests on. --port: Port number where the Appium server will start. --base-path: Base path to be used in server URL, ideally this should be /wd/hub. --use-drivers: Mention comma-delimited list of drivers to be activated. --use-plugins: Mention comma-delimited list of plugins to be activated. --log: File path where you want to save Appium server logs. --log-filters: Add log filters to get only the required logs. --log-level: Specify log levels that should be logged. --log-timestamp: Add this if you want to have timestamps in the logs. --local-timezone: Add the timezone for which you want to see the time in. --debug-log-spacing: To add extra spacing in logs for debugging. --allow-insecure: Mention all the insecure features which you want to be enabled by separating them with a comma. --default-capabilities: Specify the default capabilities which you know will not change for your tests. You can override them by passing in the driver instance when creating the session. --session-override: Add this if you want to override the existing session. --webhook: ention the webhook URL where you want Appium logs to be redirected. --strict-caps: Mention this when you want a strict check of passed capabilities. --driver-xcuitest-webdriveragent-port: Mention WebDriverAgent port number. --config: Specify the Appium config file path which Appium can use to configure. --nodeconfig: Specify the Selenium Grid configuration file to connect to a grid. --allow-cors: Use this when you want to allow Web to connect to your Appium server instance. --relaxed-security: Use this to relax security check. Start and Stop Appium Server > appium server --address localhost --port 4723 --use-drivers uiautomator2 --base-path /wd/hub --use-plugins appium-dashboard App Management Get App package name var packageName = driver.getCurrentPackage (); Get the current Activity name var activityName = this.driver.currentActivity (); Activate application driver.activateApp ("com.domain.app.package"); Terminate application driver.terminateApp ("com.domain.app.package"); Install application this.driver.installApp (""); Uninstall application this.driver.removeApp (" "); Check if the application is installed var isInstalled = this.driver.isAppInstalled (" "); Appium Java Client Start Appium Server: private AppiumDriverLocalService buildAppiumService () { final var logFile = Path.of (getProperty ("user.dir"), "logs", "appium.log") .toFile (); final var builder = new AppiumServiceBuilder (); return builder.withIPAddress (System.getProperty ("host", "127.0.0.1")) .usingPort (Integer.parseInt (System.getProperty ("port", "4723"))) .withLogFile (logFile) .withArgument (GeneralServerFlag.BASEPATH, "/wd/hub") .withArgument (GeneralServerFlag.USE_DRIVERS, "uiautomator2") .withArgument (GeneralServerFlag.USE_PLUGINS, "appium-dashboard") .withArgument (GeneralServerFlag.SESSION_OVERRIDE) .withArgument (GeneralServerFlag.ALLOW_INSECURE, "chromedriver_autodownload") .build (); } Stop Appium Server: if (this.service.isRunning ()) { this.service.stop (); } Setting Desired Capabilities: private Capabilities buildCapabilities () { final var deviceName = getProperty (DEVICE_NAME_KEY, "Pixel_6_Pro"); final var deviceVersion = getProperty (DEVICE_VERSION_KEY, "11"); final var options = new UiAutomator2Options (); options.setPlatformName ("Android") .setPlatformVersion (deviceVersion) .setDeviceName (deviceName) .setAvd (deviceName) .setApp (Path.of (getProperty ("user.dir"), "src/test/resources/proverbial.apk") .toString ()) .setAutoGrantPermissions (true) .setIsHeadless (parseBoolean (getProperty ("headless", "false"))); return options; } Start Driver Session: var capabilities = buildCapabilities (); this.service = buildAppiumService (); this.service.start (); . . . var serverUrl = this.service.getUrl (); this.driver = new AndroidDriver (serverUrl, capabilities); Stop Driver Session: this.driver.quit (); Update Driver Settings: this.driver.setSetting (Setting.KEYBOARD_AUTOCORRECTION, false); Update Driver Setting Via Capabilities: options.setCapability ("appium:settings[setting-name]", "value"); Supported Locator Strategies Accessibility ID: var element = this.driver.findElement(AppiumBy.accessibilityId ("accessibility-id")); ID: var element = this.driver.findElement(AppiumBy.id ("element-id")); Class Name: var element = AppiumBy.className ("some.class"); XPath: var element = AppiumBy.xpath (".//android.widget.Button[@text='COLOR']"); Android Ui Selector: var element = AppiumBy.androidUIAutomator ("new UiSelector().text("some-text")"); Android Data Matcher: var element = AppiumBy.androidDataMatcher (new Json ().toJson (ImmutableMap.of ( "name", "hasEntry", "args", ImmutableList.of ("title", "App") ))); Android View Matcher: var element = AppiumBy.androidViewMatcher (new Json ().toJson (ImmutableMap.of ( "name", "withText", "args", "Animation", "class", "androidx.test.espresso.matcher.ViewMatchers" ))); iOS Predicate String: var element = AppiumBy.iOSNsPredicateString ("label == "Colour" AND name == "color""); iOS Class Chain: var element = AppiumBy.iOSClassChain ("**/XCUIElementTypeButton[`label == "Colour"`]"); Device Actions Take a Screenshot: final var file = ((TakesScreenshot) this.driver).getScreenshotAs (FILE); try { FileUtils.copyFile (file, new File (fileName)); } catch (final IOException e) { e.printStackTrace (); } Get screen size: driver.manage ().window ().getSize (); Check if running on Device Browser: var isWebApp = driver.isBrowser (); Open a Deeplink: driver.get ("someapp://deeplink/to/screen"); Get Session ID: var sessionId = driver.getSessionId (); Handle Alerts: var message = this.driver.switchTo () .alert () .accept (); Switch context to WebView: driver.context ("WebView-name"); Get all the available contexts: var handles = driver.getContextHandles (); Get Battery percent level: var batteryPercent = driver.getBatteryInfo ().getLevel (); Get Battery state: var batteryState = driver.getBatteryInfo ().getState (); Check if the keyboard is visible: var isKeyboardVisible = driver.isKeyboardShown (); Hide keyboard: driver.hideKeyboard (); Android specific actions: Open Notifications panel To open the notification panel on your device, use the following command: driver.openNotifications (); Toggle Location services To toggle location services ON / OFF on the device, use the following command: driver.toggleLocationServices (); Toggle Mobile Data To toggle mobile data ON / OFF on the device, use the following command: driver.toggleData (); Toggle WiFi To toggle WiFi ON / OFF on the device, use the following command: driver.toggleWifi (); Toggle Airplane Mode To toggle Airplane mode ON / OFF on the device, use the following command: driver.toggleWifi (); Toggle Airplane Mode To toggle Airplane mode ON / OFF on the device, use the following command: driver.toggleAirplaneMode (); Lock device: driver.lockDevice (); Check if device is locked: var isLocked = driver.isDeviceLocked (); Unlock device: driver.unlockDevice (); Get Clipboard Text: var text = driver.getClipboardText (); //OR var text = driver.getClipboard (ClipboardContentType.PLAINTEXT); Video recording: // For Android var option = AndroidStartScreenRecordingOptions.startScreenRecordingOptions () .withTimeLimit (Duration.ofMinutes (5)); // For iOS final var option = IOSStartScreenRecordingOptions.startScreenRecordingOptions () .withTimeLimit (Duration.ofMinutes (5)); this.driver.startRecordingScreen (option); Video stream real-time: private void startStreaming () { final var args = new HashMap (); args.put ("host", "127.0.0.1"); args.put ("port", 8093); args.put ("quality", 75); args.put ("bitRate", 20000000); this.driver.executeScript ("mobile: startScreenStreaming", args); } Pull device file to local: byte [] fileContent = driver.pullFile ("/device/path/to/file"); Push local file to the device: try { this.driver.pushFile ("/device/path/to/folder", new File ("/local/file/path")); } catch (IOException e) { // Do some error handling } Swipe up on screen: private void swipe () { final var size = this.driver.manage () .window () .getSize (); final var start = new Point (size.getWidth () / 2, size.getHeight () / 2); final var end = new Point (start.getX (), start.getY () - (start.getY () / 2)); final var finger = new PointerInput (PointerInput.Kind.TOUCH, "Finger 1"); final var sequence = new Sequence (finger, 0); sequence.addAction ( finger.createPointerMove (Duration.ZERO, PointerInput.Origin.viewport (), start.getX (), start.getY ())); sequence.addAction (finger.createPointerDown (PointerInput.MouseButton.LEFT.asArg ())); sequence.addAction ( finger.createPointerMove (ofMillis (600), PointerInput.Origin.viewport (), end.getX (), end.getY ())); sequence.addAction (finger.createPointerUp (PointerInput.MouseButton.LEFT.asArg ())); this.driver.perform (singletonList (sequence)); } Android Emulator Device Actions Modify Network speed: driver.setNetworkSpeed (NetworkSpeed.FULL); Use Fingerprint: driver.fingerPrint (1); Update Geolocation: driver.setLocation (new AndroidGeoLocation ( , )); Get Geolocation: var location = driver.location (); App Management Get App package name: var packageName = driver.getCurrentPackage (); Get the current Activity name: var activityName = this.driver.currentActivity (); Activate application: driver.activateApp ("com.domain.app.package"); Terminate application: driver.terminateApp ("com.domain.app.package"); Install application: this.driver.installApp (" "); Uninstall application: this.driver.removeApp (" "); Check if the application is installed: var isInstalled = this.driver.isAppInstalled (" ");
Subscribe to:
Posts (Atom)