### Basic TestNG Setup with BrowserStack SDK Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/INTEGRATION_GUIDE.md Set up a basic TestNG test class with setUp and tearDown methods. The BrowserStack SDK automatically captures test metadata, status, and logs during test execution. ```java public class TestBase { @BeforeMethod public void setUp() { driver = new ChromeDriver(); // SDK automatically captures this metadata // Available in BrowserStack dashboard } @AfterMethod public void tearDown() { // SDK captures test status and logs driver.quit(); } } ``` -------------------------------- ### Inheritance Pattern Example Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/api-reference/SeleniumTest.md Demonstrates how to extend the SeleniumTest class to create specific test cases. The setUp() and tearDown() methods from the base class are automatically invoked. ```java public class BStackDemoTest extends SeleniumTest { @Test public void addProductToCart() throws Exception { // SeleniumTest.setUp() runs before this method driver.get("https://www.bstackdemo.com"); // ... test code ... // SeleniumTest.tearDown() runs after this method } } ``` -------------------------------- ### setUp() Method Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/api-reference/SeleniumTest.md Initializes a ChromeDriver instance before each test method. It configures options to maximize the browser window and ensures a fresh WebDriver session for every test. ```APIDOC ## setUp() ### Description Initializes a ChromeDriver instance with configured options. Creates a new WebDriver session for each test method, ensuring test isolation. ### Method ```java public void setUp() throws Exception ``` ### TestNG Lifecycle Executes before each test method (`@BeforeMethod`) ### Parameters None ### Return Type void ### Behavior 1. Creates `ChromeOptions` instance 2. Adds argument `start-maximized` to maximize browser window on startup 3. Instantiates `ChromeDriver` with configured options 4. Stores driver instance in the `driver` field ### Throws `Exception` - Any exception during driver initialization ### Usage Example ```java public class MyTest extends SeleniumTest { @Test public void testSomething() { // driver is ready to use here driver.get("https://example.com"); // assertions and interactions... } } ``` ``` -------------------------------- ### WebDriver Initialization in setUp() Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/api-reference/SeleniumTest.md Initializes a ChromeDriver instance with maximized window. This method runs before each test method, ensuring a fresh browser session for isolation. ```java ChromeOptions options = new ChromeOptions(); options.addArguments("start-maximized"); driver = new ChromeDriver(options); ``` -------------------------------- ### Complete BrowserStack Configuration Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/configuration.md This is a comprehensive example of a BrowserStack configuration file. It includes settings for credentials, project and build details, platform definitions for various browsers and devices, parallelization settings, BrowserStack Local configuration, and debugging options. ```yaml # ============================= # Set BrowserStack Credentials # ============================= userName: myusername accessKey: myaccesskey # ====================== # BrowserStack Reporting # ====================== projectName: My E-Commerce Tests buildName: Daily Test Run buildIdentifier: '#${BUILD_NUMBER}' framework: testng # ======================================= # Platforms (Browsers / Devices to test) # ======================================= platforms: - os: OS X osVersion: Big Sur browserName: Chrome browserVersion: latest - os: Windows osVersion: 10 browserName: Edge browserVersion: latest - deviceName: Samsung Galaxy S22 Ultra browserName: chrome osVersion: 12.0 # ======================= # Parallels per Platform # ======================= parallelsPerPlatform: 2 # Source identifier source: testng:myproject:v1.0 # ========================================== # BrowserStack Local # ========================================== browserstackLocal: true browserStackLocalOptions: localIdentifier: main-tunnel forceLocal: false # =================== # Debugging features # =================== debug: false networkLogs: true consoleLogs: warnings testObservability: true debugUtility: false ``` -------------------------------- ### Create a Test Class with SeleniumTest Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/QUICK_START.md Example of a basic TestNG test class that extends `SeleniumTest`. It navigates to a URL and asserts the page title. Ensure `SeleniumTest` is correctly implemented to provide the `driver` instance. ```java package com.yourcompany; import org.testng.Assert; import org.testng.annotations.Test; import org.openqa.selenium.By; public class MyTest extends SeleniumTest { @Test public void testMyFeature() { driver.get("https://your-website.com"); Assert.assertTrue(driver.getTitle().contains("Expected Title")); } } ``` -------------------------------- ### GitHub Actions CI/CD Integration for BrowserStack Tests Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/BUILD_AND_EXECUTION.md Configure a GitHub Actions workflow to run BrowserStack tests. This example checks out code, sets up Java, and executes Maven tests, injecting BrowserStack credentials as environment variables. ```yaml name: BrowserStack Tests on: [push, pull_request] jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: actions/setup-java@v2 with: java-version: '11' - run: mvn test -P sample-test env: BROWSERSTACK_USERNAME: ${{ secrets.BS_USERNAME }} BROWSERSTACK_ACCESS_KEY: ${{ secrets.BS_ACCESS_KEY }} ``` -------------------------------- ### Maven Commands for Dependency Management Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/BUILD_AND_EXECUTION.md Commands to compile project dependencies and install artifacts locally using Maven. ```bash mvn compile mvn clean install ``` -------------------------------- ### Maven Command to Skip Tests Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/BUILD_AND_EXECUTION.md Perform a clean install of the project while skipping all test executions. ```bash mvn clean install -DskipTests ``` -------------------------------- ### Local WebDriver Setup for Development Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/INTEGRATION_GUIDE.md Configure WebDriver to use a local ChromeDriver instance. WebDriverManager can optionally be used for automatic driver management. ```java @BeforeMethod public void setUp() { WebDriverManager.chromedriver().setup(); // Optional: auto-manage driver driver = new ChromeDriver(); // Runs locally } ``` -------------------------------- ### Maven Command for Verbose Output Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/BUILD_AND_EXECUTION.md Run Maven tests with verbose logging enabled to get detailed output during execution. ```bash mvn test -P sample-test -X ``` -------------------------------- ### WebDriver Setup for BrowserStack Cloud Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/INTEGRATION_GUIDE.md The same WebDriver code is used, but the SDK intercepts instantiation to run tests on the BrowserStack cloud. ```java @BeforeMethod public void setUp() { driver = new ChromeDriver(); // Intercepted by SDK -> BrowserStack cloud } ``` -------------------------------- ### BStackDemoTest Class Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/REFERENCE_INDEX.md The BStackDemoTest class provides a functional test example for an e-commerce website, specifically focusing on product navigation and cart interactions. ```APIDOC ## BStackDemoTest ### Description Functional test for e-commerce website (bstackdemo.com). ### Exports: - Method: `public void addProductToCart()` (annotated with @Test) ### Extends: `SeleniumTest` ### Test Scenarios: Product navigation, cart interaction, data validation ``` -------------------------------- ### Usage Example: Extending SeleniumTest Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/api-reference/SeleniumTest.md Example of a test class extending SeleniumTest to use the managed WebDriver instance. The `driver` field is directly accessible within test methods. ```java public class MyTest extends SeleniumTest { @Test public void testSomething() { // driver is ready to use here driver.get("https://example.com"); // assertions and interactions... } } ``` -------------------------------- ### Run Sample Tests with Gradle Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/QUICK_START.md Commands to build the project, run sample tests, and run local tests using Gradle. These commands are used to execute the test suites defined in your Gradle build. ```bash # Build project gradle build # Run sample tests gradle sampleTest # Run local tests gradle sampleLocalTest ``` -------------------------------- ### Build Project with Gradle Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/BUILD_AND_EXECUTION.md Commands to build the entire project using Gradle. Includes options for using the Gradle wrapper. ```bash gradle build ./gradlew build ``` -------------------------------- ### Multiple Test Methods in Single Class Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/EXAMPLES_AND_PATTERNS.md Use this pattern when you have multiple related tests that can share setup and teardown logic within a single TestNG class. Each test method runs independently with its own setup and teardown. ```java package com.browserstack; import org.testng.Assert; import org.testng.annotations.Test; import org.openqa.selenium.By; public class MultipleTests extends SeleniumTest { @Test(priority = 1) public void testPageLoads() { driver.get("https://www.bstackdemo.com"); Assert.assertNotNull(driver.getTitle()); } @Test(priority = 2) public void testProductDisplay() { driver.get("https://www.bstackdemo.com"); Assert.assertTrue( driver.findElements(By.xpath("//*[@id=\"1\"]")).size() > 0, "Product element should be visible" ); } @Test(priority = 3) public void testAddToCart() { driver.get("https://www.bstackdemo.com"); driver.findElement(By.xpath("//*[@id=\"1\"]/div[4]")).click(); Assert.assertTrue( driver.findElement(By.cssSelector(".float\-cart__content")).isDisplayed() ); } } ``` -------------------------------- ### Clean Build with Gradle Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/BUILD_AND_EXECUTION.md Command to clean previous build artifacts and then build the project. ```bash gradle clean build ``` -------------------------------- ### Run Sample Tests with Maven Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/QUICK_START.md Commands to compile, run cross-platform tests, and run local tunnel tests using Maven. The `-P` flag selects specific Maven profiles. ```bash # Install dependencies mvn compile # Run cross-platform tests mvn test -P sample-test # Run local tunnel tests mvn test -P sample-local-test ``` -------------------------------- ### Gradle Build Commands for TestNG BrowserStack Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/PROJECT_OVERVIEW.md Commands to build the project, run sample tests, and execute local tests using Gradle. These commands are used to manage the build and execution lifecycle of the project. ```bash # Build project gradle build ``` ```bash # Run sample tests gradle sampleTest ``` ```bash # Run local tests gradle sampleLocalTest ``` -------------------------------- ### Resolve Dependencies with Maven Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/INTEGRATION_GUIDE.md Use Maven commands to clean the project and install dependencies, which can resolve 'javaagent jar not found' errors. ```bash mvn clean install mvn dependency:properties ``` -------------------------------- ### Cloud Execution with Gradle Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/api-reference/BStackDemoTest.md Execute tests on the BrowserStack cloud using Gradle. This command invokes the 'sampleTest' task for cloud-based testing. ```bash gradle sampleTest ``` -------------------------------- ### Run All Tests with Gradle Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/BUILD_AND_EXECUTION.md Command to execute all tests defined in the project using Gradle. ```bash gradle test ``` -------------------------------- ### SeleniumTest Class Definition Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/api-reference/SeleniumTest.md Base class for Selenium tests, providing WebDriver instance management. Extends this class to leverage automatic setup and teardown of the WebDriver. ```java public class SeleniumTest { public WebDriver driver; @BeforeMethod(alwaysRun = true) @SuppressWarnings("unchecked") public void setUp() throws Exception { ... } @AfterMethod(alwaysRun = true) public void tearDown() throws Exception { ... } } ``` -------------------------------- ### CI/CD Integration Pattern in Java Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/EXAMPLES_AND_PATTERNS.md A TestNG class designed for integration into CI/CD pipelines, featuring tests for homepage load time, image loading, and console error checks. The `description` attribute is used to provide human-readable context for reports. ```java package com.browserstack; import org.testng.Assert; import org.testng.annotations.Test; public class CICDTest extends SeleniumTest { @Test(description = "Verify homepage loads in < 3 seconds") public void testHomePageLoadTime() { long startTime = System.currentTimeMillis(); driver.get("https://www.example.com"); long loadTime = System.currentTimeMillis() - startTime; Assert.assertTrue( loadTime < 3000, "Page should load within 3 seconds. Actual: " + loadTime + "ms" ); } @Test(description = "Verify all critical images loaded") public void testImagesLoaded() { driver.get("https://www.example.com"); int images = driver.findElements(By.cssSelector("img[complete='true']")).size(); Assert.assertTrue(images > 0, "At least one image should load"); } @Test(description = "Verify no JavaScript errors in console") public void testNoConsoleErrors() { // Requires testing in browser with console access driver.get("https://www.example.com"); // Assertions would check for console errors // Actual implementation depends on SDK capabilities } } ``` -------------------------------- ### Local Application Testing Workflow (Gradle) Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/REFERENCE_INDEX.md Run tests against a local application using Gradle. This requires 'browserstackLocal: true' in browserstack.yml and the local application running on the configured port. ```bash # Start local app at localhost:3000 npm start & # Run tests with local tunnel gradle sampleLocalTest ``` -------------------------------- ### CI/CD Pipeline Workflow (GitHub Actions) Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/REFERENCE_INDEX.md Integrate BrowserStack testing into a CI/CD pipeline using GitHub Actions. Credentials should be managed as secrets, and the 'sample-test' Maven profile is used for cloud execution. ```yaml # GitHub Actions example - run: mvn test -P sample-test env: BROWSERSTACK_USERNAME: ${{ secrets.BS_USERNAME }} BROWSERSTACK_ACCESS_KEY: ${{ secrets.BS_ACCESS_KEY }} ``` -------------------------------- ### Local Application Testing Workflow (Maven) Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/REFERENCE_INDEX.md Run tests against a local application using Maven with the 'sample-local-test' profile. This requires 'browserstackLocal: true' in browserstack.yml and the local application running on the configured port. ```bash # Start local app at localhost:3000 npm start & # Run tests with local tunnel mvn test -P sample-local-test ``` -------------------------------- ### Test Base Class with Custom Selenium Utilities (Java) Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/EXAMPLES_AND_PATTERNS.md Extend this base class to inherit common Selenium WebDriver setup, teardown, and utility methods like waiting for elements, clicking, and text retrieval. It simplifies test code by abstracting repetitive operations. ```java package com.browserstack; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.WebDriverWait; import org.openqa.selenium.support.ui.ExpectedConditions; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import java.time.Duration; public class SeleniumTestExtended { public WebDriver driver; protected static final int DEFAULT_WAIT = 10; @BeforeMethod(alwaysRun = true) public void setUp() throws Exception { driver = new ChromeDriver(); } @AfterMethod(alwaysRun = true) public void tearDown() throws Exception { driver.quit(); } /** * Wait for element to be visible and return it */ protected WebElement waitForElement(By locator) { WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(DEFAULT_WAIT)); return wait.until(ExpectedConditions.visibilityOfElementLocated(locator)); } /** * Wait for element and click it */ protected void waitAndClick(By locator) { WebElement element = waitForElement(locator); element.click(); } /** * Wait for element and get its text */ protected String waitAndGetText(By locator) { WebElement element = waitForElement(locator); return element.getText(); } /** * Check if element is present (no wait) */ protected boolean isElementPresent(By locator) { return !driver.findElements(locator).isEmpty(); } } ``` ```java public class MyTest extends SeleniumTestExtended { @Test public void testUsingUtilities() { driver.get("https://example.com"); // Uses custom wait methods String productName = waitAndGetText(By.id("product-name")); waitAndClick(By.className("add-to-cart")); if (isElementPresent(By.className("success-message"))) { System.out.println("Item added successfully"); } } } ``` -------------------------------- ### Cloud Execution with Maven Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/api-reference/BStackDemoTest.md Run tests on the BrowserStack cloud using Maven with the javaagent. This command utilizes the 'sample-test' profile for cloud execution. ```bash mvn test -P sample-test ``` -------------------------------- ### Run Single Test Class with Maven and Gradle Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/QUICK_START.md Execute a specific test class using Maven or Gradle commands. ```bash mvn test -Dtest=MyTest ``` ```bash gradle test --tests MyTest ``` -------------------------------- ### Gradle Execution Commands Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/REFERENCE_INDEX.md Commands to execute TestNG tests on BrowserStack cloud and with local tunneling using Gradle. Includes options for specific tests and full builds. ```bash gradle sampleTest # Cloud tests gradle sampleLocalTest # Local tunnel tests gradle test --tests ClassName # Specific test gradle build # Full build gradle clean build # Clean build ``` -------------------------------- ### Desktop Platform Configuration Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/REFERENCE_INDEX.md Defines the configuration for running tests on desktop browsers. Specify OS, browser name, and version. ```yaml platforms: - os: Windows|OS X|Linux osVersion: version-string browserName: Chrome|Firefox|Safari|Edge browserVersion: latest|version-number ``` -------------------------------- ### Maven Command with Custom Configuration File Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/BUILD_AND_EXECUTION.md Run Maven tests using a specified TestNG configuration file via a system property. ```bash mvn test -P sample-test -Dconfig.file=config/sample-test.testng.xml ``` -------------------------------- ### Run Cross-Platform Tests with Gradle Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/BUILD_AND_EXECUTION.md Execute cross-platform tests on the BrowserStack cloud using the 'sampleTest' Gradle task. Ensure your test suite and BrowserStack SDK are configured. ```bash gradle sampleTest ./gradlew sampleTest # Using Gradle wrapper ``` -------------------------------- ### Gradle Execution for BrowserStack Tests Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/INTEGRATION_GUIDE.md Execute tests using Gradle. Custom test tasks can be defined and run with additional logging. ```bash # Verify setup gradle build # Run custom test task gradle myCustomTests # Run with output gradle myCustomTests --info ``` -------------------------------- ### Configure BrowserStack Credentials with YAML Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/QUICK_START.md Use a `browserstack.yml` file to configure your BrowserStack username, access key, project name, build name, and platform settings. This is the recommended method for configuration. ```yaml userName: your-browserstack-username accessKey: your-browserstack-access-key projectName: My Tests buildName: Test Build buildIdentifier: '#${BUILD_NUMBER}' framework: testng platforms: - os: Windows osVersion: 10 browserName: Chrome browserVersion: latest parallelsPerPlatform: 1 ``` -------------------------------- ### Define Desktop Browser Platforms Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/configuration.md Specify the desktop browser and operating system combinations for test execution. Use `latest` for the browser version to automatically use the most recent version. ```yaml platforms: - os: OS X osVersion: Big Sur browserName: Chrome browserVersion: latest - os: Windows osVersion: 10 browserName: Edge browserVersion: latest ``` -------------------------------- ### Verify Java Agent Application for Local Testing Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/QUICK_START.md Use Maven command with -X flag to verify that the BrowserStack Java agent is correctly applied for local testing. ```bash mvn test -P sample-test -X | grep javaagent # Should see: -javaagent:/path/to/browserstack-java-sdk.jar ``` -------------------------------- ### Cloud Execution Flow with javaagent Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/REFERENCE_INDEX.md Illustrates the steps involved in executing tests on BrowserStack's cloud using the javaagent. This includes SDK initialization, test execution, and result uploading. ```text Project Root ├── JVM Start with -javaagent │ └── BrowserStack SDK Loads │ ├── Reads BROWSERSTACK_USERNAME (env or browserstack.yml) │ ├── Reads BROWSERSTACK_ACCESS_KEY (env or browserstack.yml) │ └── Parses browserstack.yml │ ├── Credentials │ ├── Platforms │ ├── Capabilities │ └── Options ├── TestNG Discovers Test Classes │ ├── SeleniumTest.setUp() runs │ │ └── new ChromeDriver() intercepted │ │ └── SDK: Connect to BrowserStack cloud │ ├── @Test method runs │ │ └── driver.get(), driver.findElement(), etc. │ │ └── SDK: Forward to cloud browser │ └── SeleniumTest.tearDown() runs │ └── driver.quit() │ └── SDK: Close cloud session └── Results Uploaded to BrowserStack Dashboard ├── Test status ├── Execution logs ├── Screenshots └── Network logs (if enabled) ``` -------------------------------- ### Configure Platforms in browserstack.yml Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/INTEGRATION_GUIDE.md Add the 'platforms' section to your browserstack.yml file to specify the testing environments. This resolves 'No platforms configured' errors. ```yaml platforms: - os: Windows osVersion: 10 browserName: Chrome browserVersion: latest ``` -------------------------------- ### Run Cloud Tests with Maven/Gradle Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/INTEGRATION_GUIDE.md Execute tests on the BrowserStack cloud using the javaagent. Ideal for CI/CD pipelines and cross-browser validation. ```bash mvn test -P browserstack # With javaagent ``` ```bash gradle browserstackTests ``` -------------------------------- ### Write TestNG Test Class Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/INTEGRATION_GUIDE.md Create a test class that extends the base class and annotates test methods with @Test. Use the 'driver' field for Selenium commands. ```java package com.yourcompany; import org.testng.Assert; import org.testng.annotations.Test; import org.openqa.selenium.By; public class MyFirstTest extends TestBase { @Test public void testGoogleSearch() { driver.get("https://www.google.com"); Assert.assertTrue(driver.getTitle().contains("Google")); } } ``` -------------------------------- ### Maven Execution Commands Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/REFERENCE_INDEX.md Commands to execute TestNG tests on BrowserStack cloud and with local tunneling using Maven. Includes options for specific tests and full builds. ```bash mvn test -P sample-test # Cloud tests mvn test -P sample-local-test # Local tunnel tests mvn test -Dtest=ClassName # Specific test mvn clean install # Full build ``` -------------------------------- ### Local Development Workflow (Gradle) Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/REFERENCE_INDEX.md Execute tests locally using Gradle without the BrowserStack profile. This runs tests using local ChromeDriver and does not utilize cloud resources. ```bash gradle test --tests MyTest ``` -------------------------------- ### Run Local Tests with Maven/Gradle Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/INTEGRATION_GUIDE.md Execute tests locally without BrowserStack cloud. Uses local ChromeDriver. Suitable for quick feedback during development. ```bash mvn test # Without -P profile, javaagent not applied ``` ```bash gradle test ``` -------------------------------- ### Maven Build Commands for TestNG BrowserStack Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/PROJECT_OVERVIEW.md Commands to compile, run cross-platform tests, and execute local tests using Maven. The `-P` flag is used to activate specific Maven profiles for test execution. ```bash # Install dependencies mvn compile ``` ```bash # Run cross-platform tests with parallelization mvn test -P sample-test ``` ```bash # Run local testing with BrowserStack Local tunnel mvn test -P sample-local-test ``` -------------------------------- ### BrowserStack Cloud Testing Platforms Configuration Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/BUILD_AND_EXECUTION.md Define the platforms for cross-browser and cross-device testing in a YAML configuration file. Supports specifying OS, browser, and device details. ```yaml platforms: - os: OS X osVersion: Big Sur browserName: Chrome browserVersion: latest - os: Windows osVersion: 10 browserName: Edge browserVersion: latest - deviceName: Samsung Galaxy S22 Ultra browserName: chrome osVersion: 12.0 ``` -------------------------------- ### Configure BrowserStack Credentials with Environment Variables Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/QUICK_START.md Alternatively, set your BrowserStack username and access key using environment variables. Ensure these are exported before running tests. ```bash export BROWSERSTACK_USERNAME=your-username export BROWSERSTACK_ACCESS_KEY=your-access-key ``` -------------------------------- ### Configure BrowserStack Local Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/QUICK_START.md Enable BrowserStack Local and configure options in browserstack.yml to route traffic through the tunnel. ```yaml browserstackLocal: true browserStackLocalOptions: forceLocal: false ``` -------------------------------- ### Run Tests with Local Application Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/QUICK_START.md Execute tests that access a local application using a Maven profile. ```bash # Ensure local app running at localhost:3000 mvn test -P sample-local-test ``` -------------------------------- ### Verify Local Application with cURL Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/api-reference/BStackLocalTest.md Use cURL to check if your local application is running and accessible on the specified port. This helps diagnose connection refused errors. ```bash curl http://localhost:45454/ ``` ```bash curl -i http://localhost:45454/ ``` -------------------------------- ### Run Gradle Task with Verbose Output Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/BUILD_AND_EXECUTION.md Execute a Gradle task with increased logging levels for debugging. Use '-i' for info level and '-d' for debug level. ```bash gradle sampleTest -i # Info level gradle sampleTest -d # Debug level ``` -------------------------------- ### Maven Command to Run All Tests Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/BUILD_AND_EXECUTION.md Execute all tests in the project using Maven. Without a profile, tests will run with local ChromeDriver. ```bash mvn test ``` -------------------------------- ### Maven Execution for BrowserStack Tests Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/INTEGRATION_GUIDE.md Use Maven to compile and run tests on BrowserStack. Ensure the javaagent is configured for BrowserStack execution. ```bash # Verify setup mvn clean compile # Run tests on BrowserStack (requires javaagent) mvn test -Dtest=MyFirstTest # Run with specific profile mvn test -P my-profile ``` -------------------------------- ### Configure 'sampleTest' Gradle Task Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/BUILD_AND_EXECUTION.md This Gradle configuration defines the 'sampleTest' task for running TestNG suites on BrowserStack. It includes dependencies, listeners, test suite specification, and JVM arguments for the BrowserStack SDK. ```gradle task sampleTest(type: Test) { useTestNG() { dependsOn cleanTest useDefaultListeners = true suites "config/sample-test.testng.xml" jvmArgs "-javaagent:${browserstackSDKArtifact.file}" } } ``` -------------------------------- ### Gradle Dependencies Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/BUILD_AND_EXECUTION.md Declare dependencies for TestNG, Selenium, BrowserStack SDK, and JSON parsing in a Gradle build file. Use `implementation` for compile and runtime dependencies, and `compileOnly` for dependencies needed only at compile time. ```gradle dependencies { implementation 'org.testng:testng:7.4.0' implementation 'org.seleniumhq.selenium:selenium-java:4.1.4' implementation 'com.browserstack:browserstack-local-java:1.0.6' implementation 'com.googlecode.json-simple:json-simple:1.1.1' compileOnly 'com.browserstack:browserstack-java-sdk:latest.release' } ``` -------------------------------- ### Maven Surefire Plugin Configuration for 'sample-test' Profile Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/BUILD_AND_EXECUTION.md This XML snippet configures the Maven Surefire plugin to use a specific TestNG suite file and applies the BrowserStack Java SDK as a javaagent for the 'sample-test' profile. ```xml sample-test org.apache.maven.plugins maven-surefire-plugin config/sample-test.testng.xml -javaagent:${com.browserstack:browserstack-java-sdk:jar} ``` -------------------------------- ### Mobile Platform Configuration Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/REFERENCE_INDEX.md Defines the configuration for running tests on mobile devices. Specify device name, browser name, and OS version. ```yaml platforms: - deviceName: device-model browserName: browser-name osVersion: os-version ``` -------------------------------- ### TestNG XML Suite Configuration Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/api-reference/BStackDemoTest.md This XML snippet shows how to configure the BStackDemoTest class to run within a TestNG test suite named 'Cross-Platform'. Ensure the class name 'com.browserstack.BStackDemoTest' is correctly specified. ```xml ``` -------------------------------- ### Maven Surefire Plugin Configuration for 'sample-local-test' Profile Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/BUILD_AND_EXECUTION.md This XML snippet configures the Maven Surefire plugin for the 'sample-local-test' profile, specifying the TestNG suite file and applying the BrowserStack Java SDK. ```xml sample-local-test org.apache.maven.plugins maven-surefire-plugin config/sample-local-test.testng.xml -javaagent:${com.browserstack:browserstack-java-sdk:jar} ``` -------------------------------- ### Initialize WebDriver with BrowserStack SDK (Java) Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/QUICK_START.md Use this to automatically initialize WebDriver. The BrowserStack SDK intercepts this call, reads the `browserstack.yml` configuration, connects to the BrowserStack cloud, and creates a remote browser session. This is typically used with the `javaagent`. ```java // Automatically intercepted by BrowserStack SDK driver = new ChromeDriver(); // With javaagent: // → SDK reads browserstack.yml // → Connects to BrowserStack cloud // → Creates remote browser session // Without javaagent: // → Local Chrome browser opens ``` -------------------------------- ### Test Selectors Locally Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/QUICK_START.md Run tests locally with the same command used for cloud execution to verify selectors and basic test logic. ```bash mvn test -Dtest=MyTest ``` -------------------------------- ### BrowserStack SDK JVM Agent Argument Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/BUILD_AND_EXECUTION.md This is the standard JVM argument format for enabling the BrowserStack SDK agent. Ensure the path to the SDK JAR is correct. ```bash -javaagent:/path/to/browserstack-java-sdk.jar ``` -------------------------------- ### Configure Local Tunneling Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/INTEGRATION_GUIDE.md Enable BrowserStack Local for testing private applications. Set `browserstackLocal` to true in your configuration. ```yaml # browserstack.yml browserstackLocal: true browserStackLocalOptions: localIdentifier: my-tunnel forceLocal: false ``` -------------------------------- ### Configure Environment-Specific BrowserStack Settings with Maven Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/INTEGRATION_GUIDE.md Use Maven profiles to switch between different BrowserStack configuration files. This allows for environment-specific settings, such as different browser configurations for CI/CD pipelines. ```xml browserstack.yml ci-parallel config/ci-parallel-browsers.yml ``` ```bash mvn test -P ci-parallel # Uses ci-parallel-browsers.yml ``` -------------------------------- ### Check BrowserStack Credentials Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/QUICK_START.md Verify BrowserStack username and access key by checking environment variables or the browserstack.yml file. ```bash # Check environment variables echo $BROWSERSTACK_USERNAME echo $BROWSERSTACK_ACCESS_KEY # Or verify browserstack.yml cat browserstack.yml | head -3 ``` -------------------------------- ### Compile Only with Gradle Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/BUILD_AND_EXECUTION.md Command to compile only the Java classes without running tests or other build steps. ```bash gradle classes ``` -------------------------------- ### Enable Debug Utility Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/configuration.md Enable the debug utility to validate the syntax and correctness of your `browserstack.yml` configuration before running tests. ```yaml debugUtility: false ``` -------------------------------- ### Run Specific Test Class with Gradle Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/BUILD_AND_EXECUTION.md Commands to run specific test classes or patterns using the Gradle test task. Supports exact class names or package patterns. ```bash gradle test --tests BStackDemoTest gradle test --tests "com.browserstack.*" ``` -------------------------------- ### TestNG Suite for Cross-Platform Testing Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/BUILD_AND_EXECUTION.md Use this XML configuration to define which test classes should be executed across different platforms via BrowserStack. ```xml ``` -------------------------------- ### TestNG Suite Configuration for Local Testing Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/api-reference/BStackLocalTest.md XML configuration for a TestNG suite designed to run tests using BrowserStack Local. This file specifies the test suite name, test group, and the class containing the test methods. ```xml ``` -------------------------------- ### Maven Command with Specific JVM Options Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/BUILD_AND_EXECUTION.md Execute Maven tests while specifying custom JVM arguments, such as setting the maximum heap size. ```bash mvn test -P sample-test -DargLine="-Xmx2g" ``` -------------------------------- ### Local Execution with Gradle Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/api-reference/BStackDemoTest.md Execute tests locally using Gradle with ChromeDriver. This command targets the BStackDemoTest class. ```bash gradle test --tests BStackDemoTest ``` -------------------------------- ### Local Execution with Maven Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/api-reference/BStackDemoTest.md Run tests locally using Maven with ChromeDriver. This command executes the BStackDemoTest class. ```bash mvn test -Dtest=BStackDemoTest ``` -------------------------------- ### Define Mobile Device Platforms Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/configuration.md Specify mobile devices and their browser configurations for test execution. Ensure `osVersion` matches the device's operating system version. ```yaml - deviceName: Samsung Galaxy S22 Ultra browserName: chrome osVersion: 12.0 ``` -------------------------------- ### Add Product to Cart Test Method Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/api-reference/BStackDemoTest.md This TestNG test method verifies the complete add-to-cart workflow on the bstackdemo.com website. It navigates to the site, adds a product, and validates the cart contents. ```java @Test public void addProductToCart() throws Exception { // navigate to bstackdemo driver.get("https://www.bstackdemo.com"); // Check the title Assert.assertTrue(driver.getTitle().matches("StackDemo")); // Save the text of the product for later verify String productOnScreenText = driver.findElement( By.xpath("//*[@id=\"1\"]/p") ).getText(); // Click on add to cart button driver.findElement(By.xpath("//*[@id=\"1\"]/div[4]")).click(); // See if the cart is opened or not Assert.assertTrue( driver.findElement(By.cssSelector(".float\-cart__content")).isDisplayed() ); // Check the product inside the cart is same as of the main page String productOnCartText = driver.findElement( By.xpath("//*[@id=\"__next\"]/div/div/div[2]/div[2]/div[2]/div/div[3]/p[1]") ).getText(); Assert.assertEquals(productOnScreenText, productOnCartText); } ``` -------------------------------- ### Run Tests with Local Tunnel Enabled Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/INTEGRATION_GUIDE.md Execute tests using Maven with the BrowserStack profile, which includes enabling the local tunnel for private application testing. ```bash mvn test -P browserstack # With local tunnel enabled ``` -------------------------------- ### Interact with Elements and Verify Cart Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/EXAMPLES_AND_PATTERNS.md Finds product elements, simulates adding to cart, and verifies the cart's state and content. Uses XPath and CSS selectors for element location. ```java package com.browserstack; import org.testng.Assert; import org.testng.annotations.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; public class InteractionTest extends SeleniumTest { @Test public void testAddToCart() throws Exception { // Navigate driver.get("https://www.bstackdemo.com"); // Find product element by XPath WebElement productText = driver.findElement(By.xpath("//*[@id=\"1\"]/p")); String expectedProduct = productText.getText(); // Find and click add-to-cart button WebElement addToCartButton = driver.findElement(By.xpath("//*[@id=\"1\"]/div[4]")); addToCartButton.click(); // Verify cart is displayed WebElement cartContent = driver.findElement(By.cssSelector(".float\-cart__content")); Assert.assertTrue( cartContent.isDisplayed(), "Shopping cart should be visible after adding item" ); // Verify product in cart matches original WebElement cartProduct = driver.findElement( By.xpath("//*[@id=\"__next\"]/div/div/div[2]/div[2]/div[2]/div/div[3]/p[1]") ); Assert.assertEquals( cartProduct.getText(), expectedProduct, "Product text in cart should match product on main page" ); } } ``` -------------------------------- ### Configure Parallel Cross-Browser Testing with browserstack.yml Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/INTEGRATION_GUIDE.md Define the number of parallels per platform and specify the target platforms for your tests. This configuration enables running multiple test sessions concurrently across different browsers and devices. ```yaml # browserstack.yml parallelsPerPlatform: 2 platforms: - os: Windows osVersion: 10 browserName: Chrome browserVersion: latest - os: OS X osVersion: Monterey browserName: Safari browserVersion: latest - deviceName: iPhone 13 browserName: safari osVersion: 15.0 ``` -------------------------------- ### Configure TestNG Suite XML Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/INTEGRATION_GUIDE.md Define the test suite XML file to specify which test classes to execute. Key attributes include suite name and test group name. ```xml ``` -------------------------------- ### Running Gradle Tests with Local Tunnel Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/api-reference/BStackLocalTest.md Execute Gradle tests configured to run with the BrowserStack Local tunnel. This command initiates tests on BrowserStack's cloud, tunneling to your local environment. ```bash # Gradle - runs on BrowserStack with Local tunnel gradle sampleLocalTest ``` -------------------------------- ### Configure Maven Surefire Plugin for BrowserStack Source: https://github.com/browserstack/testng-browserstack/blob/master/README.md Configure the maven-surefire-plugin to use the BrowserStack Java agent and specify the test suite XML file. ```xml maven-dependency-plugin getClasspathFilenames properties org.apache.maven.plugins maven-surefire-plugin 3.0.0-M5 config/sample-local-test.testng.xml -javaagent:${com.browserstack:browserstack-java-sdk:jar} ``` -------------------------------- ### Run Local Tunneling Tests with Gradle Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/BUILD_AND_EXECUTION.md Execute local tunneling tests using the 'sampleLocalTest' Gradle task. This task is configured similarly to 'sampleTest' but targets a different test suite. ```bash gradle sampleLocalTest ./gradlew sampleLocalTest ``` -------------------------------- ### Verify BrowserStack Credentials Source: https://github.com/browserstack/testng-browserstack/blob/master/_autodocs/INTEGRATION_GUIDE.md Check your BrowserStack credentials by viewing the browserstack.yml file or by setting environment variables. This helps resolve 'Invalid credentials' issues. ```bash # Verify credentials in browserstack.yml cat browserstack.yml | grep -E "userName|accessKey" # Or use environment variables export BROWSERSTACK_USERNAME=correct-username export BROWSERSTACK_ACCESS_KEY=correct-key mvn test -P browserstack ```