Best io.appium code snippet using io.appium.java_client.remote.SupportsContextSwitching
GenericWebDriverManagerTests.java
Source:GenericWebDriverManagerTests.java  
...49import org.openqa.selenium.remote.CapabilityType;50import org.vividus.selenium.IWebDriverProvider;51import io.appium.java_client.ios.IOSDriver;52import io.appium.java_client.remote.MobilePlatform;53import io.appium.java_client.remote.SupportsContextSwitching;54@ExtendWith(MockitoExtension.class)55class GenericWebDriverManagerTests56{57    private static final String NATIVE_APP_CONTEXT = "NATIVE_APP";58    private static final String WEBVIEW_CONTEXT = "WEBVIEW_1";59    @Mock private IWebDriverProvider webDriverProvider;60    @Mock private IWebDriverManagerContext webDriverManagerContext;61    @InjectMocks private GenericWebDriverManager driverManager;62    private WebDriver mockWebDriver(Object platform)63    {64        var capabilities = mock(Capabilities.class);65        when(capabilities.getCapability(CapabilityType.PLATFORM_NAME)).thenReturn(platform);66        var webDriver = mock(WebDriver.class, withSettings().extraInterfaces(HasCapabilities.class));67        when(webDriverProvider.get()).thenReturn(webDriver);68        when(((HasCapabilities) webDriver).getCapabilities()).thenReturn(capabilities);69        return webDriver;70    }71    private void mockMobileDriverContext(SupportsContextSwitching contextSwitchingDriver,72            Set<String> returnContextHandles)73    {74        when(webDriverProvider.getUnwrapped(SupportsContextSwitching.class)).thenReturn(contextSwitchingDriver);75        when(contextSwitchingDriver.getContext()).thenReturn(WEBVIEW_CONTEXT);76        when(contextSwitchingDriver.getContextHandles()).thenReturn(returnContextHandles);77    }78    private GenericWebDriverManager spyIsMobile(boolean returnValue)79    {80        var spy = Mockito.spy(driverManager);81        doReturn(returnValue).when(spy).isMobile();82        return spy;83    }84    @Test85    void testPerformActionInNativeContextNotMobile()86    {87        var webDriverConfigured = mock(WebDriver.class);88        when(webDriverProvider.get()).thenReturn(webDriverConfigured);89        GenericWebDriverManager spy = spyIsMobile(false);90        spy.performActionInNativeContext(webDriver -> assertEquals(webDriverConfigured, webDriver));91        verifyNoInteractions(webDriverConfigured);92    }93    @Test94    void testPerformActionInNativeContext()95    {96        var contextSwitchingDriver = mock(SupportsContextSwitching.class,97                withSettings().extraInterfaces(HasCapabilities.class));98        Set<String> contexts = new HashSet<>();99        contexts.add(WEBVIEW_CONTEXT);100        contexts.add(NATIVE_APP_CONTEXT);101        mockMobileDriverContext(contextSwitchingDriver, contexts);102        var spy = spyIsMobile(true);103        spy.performActionInNativeContext(webDriver -> assertEquals(contextSwitchingDriver, webDriver));104        verify(contextSwitchingDriver).context(NATIVE_APP_CONTEXT);105        verify(contextSwitchingDriver).context(WEBVIEW_CONTEXT);106    }107    @Test108    void testPerformActionInNativeContextException()109    {110        var contextSwitchingDriver = mock(SupportsContextSwitching.class,111                withSettings().extraInterfaces(HasCapabilities.class));112        mockMobileDriverContext(contextSwitchingDriver, new HashSet<>());113        var spy = spyIsMobile(true);114        var exception = assertThrows(IllegalStateException.class,115                () -> spy.performActionInNativeContext(webDriver -> assertEquals(contextSwitchingDriver, webDriver)));116        assertEquals("MobileDriver doesn't have context: " + NATIVE_APP_CONTEXT, exception.getMessage());117    }118    @Test119    void testPerformActionInNativeContextSwitchNotNeeded()120    {121        var contextSwitchingDriver = mock(SupportsContextSwitching.class);122        when(webDriverProvider.getUnwrapped(SupportsContextSwitching.class)).thenReturn(contextSwitchingDriver);123        when(contextSwitchingDriver.getContext()).thenReturn(NATIVE_APP_CONTEXT);124        var spy = spyIsMobile(true);125        spy.performActionInNativeContext(webDriver -> assertEquals(contextSwitchingDriver, webDriver));126        verify(contextSwitchingDriver, never()).context(NATIVE_APP_CONTEXT);127        verify(contextSwitchingDriver, never()).getContextHandles();128    }129    static Stream<Arguments> mobileArguments()130    {131        // CHECKSTYLE:OFF132        return Stream.of(133            arguments((Predicate<GenericWebDriverManager>) GenericWebDriverManager::isMobile, MobilePlatform.IOS, true),134            arguments((Predicate<GenericWebDriverManager>) GenericWebDriverManager::isMobile, MobilePlatform.ANDROID, true),135            arguments((Predicate<GenericWebDriverManager>) GenericWebDriverManager::isMobile, MobilePlatform.WINDOWS, false),136            arguments((Predicate<GenericWebDriverManager>) GenericWebDriverManager::isMobile, Platform.IOS, true),137            arguments((Predicate<GenericWebDriverManager>) GenericWebDriverManager::isMobile, Platform.ANDROID, true),138            arguments((Predicate<GenericWebDriverManager>) GenericWebDriverManager::isMobile, Platform.WINDOWS, false),139            arguments((Predicate<GenericWebDriverManager>) GenericWebDriverManager::isIOS, MobilePlatform.IOS, true),140            arguments((Predicate<GenericWebDriverManager>) GenericWebDriverManager::isIOS, MobilePlatform.ANDROID, false),141            arguments((Predicate<GenericWebDriverManager>) GenericWebDriverManager::isIOS, Platform.IOS, true),142            arguments((Predicate<GenericWebDriverManager>) GenericWebDriverManager::isIOS, Platform.ANDROID, false),143            arguments((Predicate<GenericWebDriverManager>) GenericWebDriverManager::isAndroid, MobilePlatform.IOS, false),144            arguments((Predicate<GenericWebDriverManager>) GenericWebDriverManager::isAndroid, MobilePlatform.ANDROID, true),145            arguments((Predicate<GenericWebDriverManager>) GenericWebDriverManager::isAndroid, Platform.IOS, false),146            arguments((Predicate<GenericWebDriverManager>) GenericWebDriverManager::isAndroid, Platform.ANDROID, true),147            arguments((Predicate<GenericWebDriverManager>) GenericWebDriverManager::isTvOS, MobilePlatform.TVOS, true),148            arguments((Predicate<GenericWebDriverManager>) GenericWebDriverManager::isTvOS, MobilePlatform.IOS, false),149            arguments((Predicate<GenericWebDriverManager>) GenericWebDriverManager::isTvOS, Platform.IOS, false),150            arguments((Predicate<GenericWebDriverManager>) GenericWebDriverManager::isIOS, null, false)151        );152        // CHECKSTYLE:ON153    }154    @ParameterizedTest155    @MethodSource("mobileArguments")156    void testIsPlatform(Predicate<GenericWebDriverManager> test, Object platform, boolean expected)157    {158        mockWebDriver(platform);159        assertEquals(expected, test.test(driverManager));160    }161    static Stream<Arguments> mobileNativeArguments()162    {163        // CHECKSTYLE:OFF164        return Stream.of(165                arguments((Predicate<GenericWebDriverManager>) GenericWebDriverManager::isAndroidNativeApp, MobilePlatform.ANDROID, true),166                arguments((Predicate<GenericWebDriverManager>) GenericWebDriverManager::isAndroidNativeApp, MobilePlatform.IOS, false),167                arguments((Predicate<GenericWebDriverManager>) GenericWebDriverManager::isIOSNativeApp, MobilePlatform.IOS, true),168                arguments((Predicate<GenericWebDriverManager>) GenericWebDriverManager::isIOSNativeApp, "ios", true),169                arguments((Predicate<GenericWebDriverManager>) GenericWebDriverManager::isIOSNativeApp, MobilePlatform.ANDROID, false)170        );171        // CHECKSTYLE:ON172    }173    @ParameterizedTest174    @MethodSource("mobileNativeArguments")175    void testIsMobileNativeApp(Predicate<GenericWebDriverManager> test, Object platform, boolean expected)176    {177        driverManager.setMobileApp(true);178        mockWebDriver(platform);179        assertEquals(expected, test.test(driverManager));180    }181    static Stream<Arguments> notMobileNativeArguments()182    {183        return Stream.of(184                arguments((Predicate<GenericWebDriverManager>) GenericWebDriverManager::isAndroidNativeApp),185                arguments((Predicate<GenericWebDriverManager>) GenericWebDriverManager::isIOSNativeApp)186        );187    }188    @ParameterizedTest189    @MethodSource("notMobileNativeArguments")190    void testIsNotMobileNativeApp(Predicate<GenericWebDriverManager> test)191    {192        driverManager.setMobileApp(false);193        assertFalse(test.test(driverManager));194    }195    @Test196    void testGetSize()197    {198        WebDriver webDriver = mockWebDriver(Platform.WINDOWS);199        var screenSize = mock(Dimension.class);200        mockSizeRetrieval(webDriver, screenSize);201        assertEquals(screenSize, driverManager.getSize());202    }203    @Test204    void shouldGetScreenSizeForMobileApp()205    {206        var dimension = new Dimension(375, 667);207        var iOSDriver = mock(IOSDriver.class);208        lenient().when(webDriverProvider.getUnwrapped(SupportsContextSwitching.class)).thenReturn(iOSDriver);209        when(iOSDriver.getContext()).thenReturn(NATIVE_APP_CONTEXT);210        mockWebDriver(MobilePlatform.IOS);211        mockSizeRetrieval(iOSDriver, dimension);212        assertEquals(dimension, driverManager.getSize());213        verify(webDriverManagerContext).putParameter(WebDriverManagerParameter.SCREEN_SIZE, dimension);214    }215    private void mockSizeRetrieval(WebDriver webDriver, Dimension screenSize)216    {217        var options = mock(Options.class);218        when(webDriver.manage()).thenReturn(options);219        var window = mock(Window.class);220        when(options.window()).thenReturn(window);221        when(window.getSize()).thenReturn(screenSize);222    }...AndroidDriver.java
Source:AndroidDriver.java  
...35import io.appium.java_client.android.connection.HasNetworkConnection;36import io.appium.java_client.android.geolocation.SupportsExtendedGeolocationCommands;37import io.appium.java_client.android.nativekey.PressesKey;38import io.appium.java_client.battery.HasBattery;39import io.appium.java_client.remote.SupportsContextSwitching;40import io.appium.java_client.remote.SupportsLocation;41import io.appium.java_client.remote.SupportsRotation;42import io.appium.java_client.screenrecording.CanRecordScreen;43import io.appium.java_client.service.local.AppiumDriverLocalService;44import io.appium.java_client.service.local.AppiumServiceBuilder;45import io.appium.java_client.ws.StringWebSocketClient;46import org.openqa.selenium.Capabilities;47import org.openqa.selenium.Platform;48import org.openqa.selenium.remote.HttpCommandExecutor;49import org.openqa.selenium.remote.html5.RemoteLocationContext;50import org.openqa.selenium.remote.http.HttpClient;51import java.net.URL;52import java.util.Collections;53import java.util.Map;54/**55 * Android driver implementation.56 */57public class AndroidDriver extends AppiumDriver implements58        PressesKey,59        SupportsRotation,60        SupportsContextSwitching,61        SupportsLocation,62        PerformsTouchActions,63        HidesKeyboard,64        HasDeviceTime,65        PullsFiles,66        InteractsWithApps,67        SupportsLegacyAppManagement,68        HasAppStrings,69        HasNetworkConnection,70        PushesFiles,71        StartsActivity,72        LocksDevice,73        HasAndroidSettings,74        HasAndroidDeviceDetails,...IOSDriver.java
Source:IOSDriver.java  
...29import io.appium.java_client.PerformsTouchActions;30import io.appium.java_client.PushesFiles;31import io.appium.java_client.SupportsLegacyAppManagement;32import io.appium.java_client.battery.HasBattery;33import io.appium.java_client.remote.SupportsContextSwitching;34import io.appium.java_client.remote.SupportsLocation;35import io.appium.java_client.remote.SupportsRotation;36import io.appium.java_client.screenrecording.CanRecordScreen;37import io.appium.java_client.service.local.AppiumDriverLocalService;38import io.appium.java_client.service.local.AppiumServiceBuilder;39import io.appium.java_client.ws.StringWebSocketClient;40import org.openqa.selenium.Alert;41import org.openqa.selenium.Capabilities;42import org.openqa.selenium.Platform;43import org.openqa.selenium.remote.DriverCommand;44import org.openqa.selenium.remote.HttpCommandExecutor;45import org.openqa.selenium.remote.Response;46import org.openqa.selenium.remote.html5.RemoteLocationContext;47import org.openqa.selenium.remote.http.HttpClient;48import java.net.URL;49import java.util.Collections;50import java.util.Map;51/**52 * iOS driver implementation.53 */54public class IOSDriver extends AppiumDriver implements55        SupportsContextSwitching,56        SupportsRotation,57        SupportsLocation,58        HidesKeyboard,59        HasDeviceTime,60        PullsFiles,61        InteractsWithApps,62        SupportsLegacyAppManagement,63        HasAppStrings,64        PerformsTouchActions,65        HidesKeyboardWithKeyName,66        ShakesDevice,67        HasIOSSettings,68        HasOnScreenKeyboard,69        LocksDevice,...GenericWebDriverManager.java
Source:GenericWebDriverManager.java  
...26import org.openqa.selenium.remote.CapabilityType;27import org.vividus.selenium.IWebDriverProvider;28import org.vividus.selenium.WebDriverUtil;29import io.appium.java_client.remote.MobilePlatform;30import io.appium.java_client.remote.SupportsContextSwitching;31public class GenericWebDriverManager implements IGenericWebDriverManager32{33    private final IWebDriverProvider webDriverProvider;34    private final IWebDriverManagerContext webDriverManagerContext;35    private boolean mobileApp;36    public GenericWebDriverManager(IWebDriverProvider webDriverProvider,37            IWebDriverManagerContext webDriverManagerContext)38    {39        this.webDriverProvider = webDriverProvider;40        this.webDriverManagerContext = webDriverManagerContext;41    }42    @Override43    public Dimension getSize()44    {45        if (!isMobile())46        {47            return getSize(webDriverProvider.get());48        }49        Dimension screenSize = webDriverManagerContext.getParameter(WebDriverManagerParameter.SCREEN_SIZE);50        if (screenSize == null)51        {52            screenSize = runInNativeContext(this::getSize);53            webDriverManagerContext.putParameter(WebDriverManagerParameter.SCREEN_SIZE, screenSize);54        }55        return screenSize;56    }57    @Override58    public void performActionInNativeContext(Consumer<WebDriver> consumer)59    {60        runInNativeContext(webDriver -> {61            consumer.accept(webDriver);62            return webDriver;63        });64    }65    private Dimension getSize(WebDriver webDriver)66    {67        return webDriver.manage().window().getSize();68    }69    private <R> R runInNativeContext(Function<WebDriver, R> function)70    {71        if (isMobile())72        {73            SupportsContextSwitching contextSwitchingDriver = getUnwrappedDriver(SupportsContextSwitching.class);74            String originalContext = contextSwitchingDriver.getContext();75            if (!NATIVE_APP_CONTEXT.equals(originalContext))76            {77                switchToContext(contextSwitchingDriver, NATIVE_APP_CONTEXT);78                try79                {80                    return function.apply(contextSwitchingDriver);81                }82                finally83                {84                    switchToContext(contextSwitchingDriver, originalContext);85                }86            }87            return function.apply(contextSwitchingDriver);...WebDriverUtilTests.java
Source:WebDriverUtilTests.java  
...29import org.openqa.selenium.virtualauthenticator.HasVirtualAuthenticator;30import org.vividus.selenium.driver.TextFormattingWebDriver;31import org.vividus.selenium.element.DelegatingWebElement;32import org.vividus.selenium.element.TextFormattingWebElement;33import io.appium.java_client.remote.SupportsContextSwitching;34class WebDriverUtilTests35{36    @Test37    void testWrappedWebDriverUnwrap()38    {39        var remoteWebDriver = mock(RemoteWebDriver.class);40        var wrappingDriver = new TextFormattingWebDriver(remoteWebDriver);41        var actual = WebDriverUtil.unwrap(wrappingDriver, HasVirtualAuthenticator.class);42        assertEquals(remoteWebDriver, actual);43    }44    @Test45    void testNonWrappedWebDriverUnwrap()46    {47        var remoteWebDriver = mock(RemoteWebDriver.class);48        var actual = WebDriverUtil.unwrap(remoteWebDriver, HasVirtualAuthenticator.class);49        assertEquals(remoteWebDriver, actual);50    }51    @Test52    void testWrappedWebDriverUnwrapButNoCast()53    {54        var webDriver = mock(WebDriver.class);55        var wrappingDriver = new TextFormattingWebDriver(webDriver);56        assertThrows(ClassCastException.class,57                () -> WebDriverUtil.unwrap(wrappingDriver, HasVirtualAuthenticator.class));58    }59    @Test60    void testWrappedWebElementUnwrap()61    {62        var remoteWebElement = mock(RemoteWebElement.class);63        var wrappingElement = new TextFormattingWebElement(remoteWebElement);64        var actual = WebDriverUtil.unwrap(wrappingElement, WrapsDriver.class);65        assertEquals(remoteWebElement, actual);66    }67    @Test68    void testWrappedWebElementWithNewInterfaceUnwrap()69    {70        var webElement = mock(SupportsContextSwitching.class, withSettings().extraInterfaces(WebElement.class));71        var actual = WebDriverUtil.unwrap(new TestWebElement((WebElement) webElement), SupportsContextSwitching.class);72        assertEquals(webElement, actual);73    }74    @Test75    void testNonWrappedWebElementUnwrap()76    {77        var remoteWebElement = mock(RemoteWebElement.class);78        var actual = WebDriverUtil.unwrap(remoteWebElement, WrapsDriver.class);79        assertEquals(remoteWebElement, actual);80    }81    @Test82    void testWrappedWebElementUnwrapButNoCast()83    {84        var webElement = mock(WebElement.class);85        var wrappingElement = new TextFormattingWebElement(webElement);...SupportsContextSwitching.java
Source:SupportsContextSwitching.java  
...26import java.util.LinkedHashSet;27import java.util.List;28import java.util.Set;29import static com.google.common.base.Preconditions.checkNotNull;30public interface SupportsContextSwitching extends WebDriver, ContextAware, ExecutesMethod {31    /**32     * Switches to the given context.33     *34     * @param name The name of the context to switch to.35     * @return self instance for chaining.36     */37    default WebDriver context(String name) {38        checkNotNull(name, "Must supply a context name");39        try {40            execute(DriverCommand.SWITCH_TO_CONTEXT, ImmutableMap.of("name", name));41            return this;42        } catch (WebDriverException e) {43            throw new NoSuchContextException(e.getMessage(), e);44        }...SupportsContextSwitching
Using AI Code Generation
1package appium;2import java.net.MalformedURLException;3import java.net.URL;4import java.util.Set;5import org.openqa.selenium.By;6import org.openqa.selenium.WebDriver;7import org.openqa.selenium.WebElement;8import org.openqa.selenium.remote.DesiredCapabilities;9import org.openqa.selenium.support.ui.ExpectedConditions;10import org.openqa.selenium.support.ui.WebDriverWait;11import io.appium.java_client.AppiumDriver;12import io.appium.java_client.android.AndroidDriver;13import io.appium.java_client.remote.MobileCapabilityType;14import io.appium.java_client.remote.MobilePlatform;15public class ContextSwitching {16	public static void main(String[] args) {17		DesiredCapabilities capabilities = new DesiredCapabilities();18		capabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, MobilePlatform.ANDROID);19		capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Android Device");20		capabilities.setCapability("appPackage", "com.androidsample.generalstore");21		capabilities.setCapability("appActivity", ".SplashActivity");22		AppiumDriver<WebElement> driver = null;23		try {SupportsContextSwitching
Using AI Code Generation
1driver.context("WEBVIEW_1");2driver.context("NATIVE_APP");3driver.context("WEBVIEW_1");4driver.context("NATIVE_APP");5driver.context("WEBVIEW_1");6driver.context("NATIVE_APP");7driver.context("WEBVIEW_1");8driver.context("NATIVE_APP");9driver.context("WEBVIEW_1");10driver.context("NATIVE_APP");11driver.context("WEBVIEW_1");12driver.context("NATIVE_APP");13driver.context("WEBVIEW_1");14driver.context("NATIVE_APP");15driver.context("WEBVIEW_1");Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
