How to reuse browser window among TestMethods in CodedUI?

Below code helps to reuse opened browser:-

BrowserWindow driver;

[TestMethod]
public void CaptureScreenshot()
{

driver = BrowserWindow.Launch(new System.Uri(“https://www.facebook.com”));
driver.TechnologyName = “Web”;
driver.CloseOnPlaybackCleanup = false;
driver.Maximized = true;

}

[TestMethod]
public void secondtest()
{
driver = new BrowserWindow();
driver.SearchProperties.Add(“Title”, “Welcome to Facebook – Log In, Sign Up or Learn More”);

HtmlEdit usr = new HtmlEdit(driver);
usr.SearchProperties.Add(“Id”, “email”);
usr.SetProperty(“Text”, “technicalt”);
}

How to take screenshots in CodedUI?

Below code will help to take entire screen screenshot-

Image MyScreenshot;
BrowserWindow driver;

[TestMethod]
public void CaptureScreenshot()
{

driver = BrowserWindow.Launch(new System.Uri(“https://www.facebook.com”));
driver.TechnologyName = “Web”;
driver.CloseOnPlaybackCleanup = false;
driver.Maximized = true;
MyScreenshot = driver.CaptureImage();
MyScreenshot.Save(@”D:\Windowscreenshot.png”, System.Drawing.Imaging.ImageFormat.Png);

}

If we need to take screenshot of any particular UI object then we can use below code-

Image MyScreenshot;
BrowserWindow driver;

[TestMethod]
public void CaptureScreenshot()
{

driver = BrowserWindow.Launch(new System.Uri(“https://www.facebook.com”));
driver.TechnologyName = “Web”;
driver.CloseOnPlaybackCleanup = false;
driver.Maximized = true;
MyScreenshot = driver.CaptureImage();
MyScreenshot.Save(@”D:\Windowscreenshot.png”, System.Drawing.Imaging.ImageFormat.Png);

HtmlLabel Login = new HtmlLabel(driver);
Login.SearchProperties.Add(“id”, “loginbutton”);

MyScreenshot = Login.CaptureImage();
MyScreenshot.Save(@”D:\Buttoncreenshot.png”, System.Drawing.Imaging.ImageFormat.Png);

}

How to keep the browser open after a CodedUI test finishes?

When we run our first CodedUI test method we notice that system closes the browser after finishing the test method and we just wonder why it closes the browser. So answer is, CodedUI framework has been designed like that only where it closes the browser after finishing the tasks.

Same framework has provided an option where we can choose not to close browser after finishing the tasks and that option is ‘CloseOnPlaybackCleanup’ property. By using this property we can make sure that browser should not close after completing the tasks.

However, in most of cases Tester writes only a method and uses CloseOnPlaybackCleanup=false and thinks that framework should not close the browser but it does not work in this way.

CloseOnPlaybackCleanup=false says that if you have more than 1 test methods and then framework will not close the browser after the first method, it will complete all test methods tasks and then only it closes the browser. So where tester has only 1 [TestMethod] with CloseOnPlaybackCleanup=false and CodedUI closes the browser there it is working as expected.

Use below code to test it out-

CloseBrowser