Pages

Tuesday, December 31, 2013

TestContext.BeginTimer() not writing to test output in VS2013


I am running Visual Studio 2013 Ultimate and can't get TestContext.BeginTimer("TimerName"); and TestContext.EndTimer("TimerName"); to write to the Output window of a CodedUI Test.

This post has a good solution to the issue.

I want to log the duration for groups of test steps.

First I tried writing a logger class and sending the duration to a text file.

This way seems easier to me:

1. Open the Coded UI Test .cs file and add a using statement for System.Diagnostics;


2. Create new instance of Stopwatch and give it some name (Timer in the example), add Timer.Start(); and Timer.Stop(); statements around actions that you're logging duration of, then add statement to write to test output TestContext.WriteLine("Description: " + SomeName.Elapsed.ToString());


3. Reset the timer next time and you can reuse it:


4. Run the test from Test Explorer, select the CodedUITestMethod in the upper pane under Passed Tests, and then click the Output link in the lower portion to view duration.

5. The output window will also show debug trace messages if EqtTraceLevel is set to 4 in QTAgent32.exe.config. TestContext messages are below the Debug Trace messages.



1 comment:

Charles Morrison said...

According to the following Microsoft blog, http://blogs.msdn.com/b/geoffgr/archive/2014/08/05/adding-timers-to-coded-ui-tests-running-in-load-tests.aspx, the ability to use timers in a Unit test was removed from Visual Stuido 2012. The blog states that the timer still works when a unit test is placed inside a load test, but standalone, the unit test will throw the System.NotSupportedException. The blog states that a workaround is to use the following line of code just before the beginTimer() call:

if (TestContext.Properties.Contains("$LoadTestUserContext")) //running as load
textContextInstance.BeginTimer("MyTimerName");

This approach is working on my installation of VS2012, and allows me to have the timers in my unit test and to run it as a single user without putting it in a load test. Removing the functionality in VS 2012 was NOT a swift move by Microsoft. I have found some cases where a timer in unit tests still does not work in VS 2013, but then sometimes it will work in 2013. In any case, in VS 2012, "unit test timers" are consistently broken but the above line of code provides a workaround.