Tuesday 20 January 2015

Why does application close after each test in Coded UI Test


In Coded UI, a flag CloseOnPlaybackCleanup is added to ApplicationUnderTest class. 
For cases where an application is launched during test run, this flag helps determine whether to close the application under test after test is over.  Default value for the flag was set to true (closes the application) as it is not advisable to re-use resources from other test cases. 
This works fine for Visual Studio 2012 and later versions. Users will see  BrowserWindow / ApplicationUnderTest is getting closed after each test case if they don't have CloseOnPlaybackCleanup flag set to false. 
 If you want to reuse any application instance launched in another test case, you have to assign CloseOnPlaybackCleanup flag to false for ApplicationUnderTest / BrowserWindow object.
Please refer to sample code as below. If you run all these three tests together, BrowserWindow will be launched only once, remaining other tests will use existing browser instance from the previous test. If you run each test individually, then each test case will close the browser at the end of the run.

public class CodedUITest1
    {
        public CodedUITest1()
        {
        }

        [TestMethod]
        public void CodedUITestMethod1()
        {
           LoadLocalHost();
        }

        [TestMethod]
        public void CodedUITestMethod2()
        {
            LoadLocalHost();
        }

        [TestMethod]
        public void CodedUITestMethod3()
        {
            LoadLocalHost();
        }


        static BrowserWindow browserWindowInstance = null;

        public void LoadLocalHost()
        {
            if (browserWindowInstance == null)
            {
                browserWindowInstance = BrowserWindow.Launch(new System.Uri("http://google.com/"));
                browserWindowInstance.CloseOnPlaybackCleanup = false;
                browserWindowInstance.Maximized = !browserWindowInstance.Maximized;
            }
            else
            {
                browserWindowInstance.Maximized = !browserWindowInstance.Maximized;
            }
        }
}     

The same principle is applied with running tests using Command Line. If you are running tests altogether, the Application Under test will remain open in between tests in case CloseOnPlaybackCleanup is set to false. Once the run is over, all application instances which were launched during the run are closed.

No comments:

Post a Comment