Sunday, 2 November 2014

Resizing browser window using CodedUI


How to test your websites responsive UI design with codedUI.
The main requirement here is that you would be able to check if you can enter values on a specific screen in different browsers in different window sizes.
So starting the browser in CodedUI is simple, you just use the BrowserWindow class and call the Launch method to start the browser in a reliable way. Starting different browsers (Chrome, firefox) is also possible by just setting theBrowserWindow.CurrentBrowser to a value of “chrome” or “firefox” so that is already solved.
The main issue is the size of the browser window. For the responsive UI to show, you need to run a test case in e.g. different screen sizes. Unfortunately there is no method on the BrowserWindow class to set the screen size of the browser.
But there is an easy fix for that.
The BrowserWIndow class has a property called WindowHandle. We can use this property to call a windows API to resize the window.
First an extension method if to be defined as below.
    public static class BrowserWindowExtensions
    {
        [DllImport("user32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        internal static extern bool SetWindowPos(IntPtr hWnd, IntPtr hwndInsertAfter, int x, int y, int cx, int cy, uint uFlags);
        public static void ResizeWindow(this BrowserWindow control, int width, int height)
        {
            SetWindowPos(control.WindowHandle, (IntPtr)(-1), 0, 0, width, height, 0x0002 | 0x0040);
        }
    }
then the TestMethod looks as shown below
        [TestMethod]
        public void BrowserResizing()
        {
            //define for Chrome
            BrowserWindow.CurrentBrowser = "Chrome";
            BrowserWindow myb = BrowserWindow.Launch();
            myb.NavigateToUrl(new System.Uri("http://bing.com/"));
            myb.Maximized = true;
            BrowserWindowExtensions.ResizeWindow(myb, 480, 800);
        }
the same is applicable for IE and Firefox.