Friday, August 16, 2013

Test Explorer is not updated properly when a test fails inside an async task

I am working on Windows Phone 8 Mobile App and when I am running a Unit Test case ,It does not showing the test status for a failed test. Instead it  is displaying the below message in Output/Tests window

"The active Test Run was aborted because the execution process exited unexpectedly.".

When I re run my Test case using Resharper, it is saying that "The Test wasn't run".

After some research , I came to know is When ever we are testing Silverlight UI Controls, We need to run the test cases, in a Separate Thread, otherwise the debugger will throw an Access denied to Main thread exception.

But When we run our test cases on a separate thread, We should not write any Assert statements in that thread , instead we need to write Assertions in the main thread. This is because of a known bug in the Visual Studio.

Visual studio will end the debug process when ever a failed Assertion occurs inside of the Child thread and there will be no intimation of this status to the Main thread. So what we need to do is create a variable in the main thread and save the Assertion status in that   variable in Child thread and use that variable to Raise Assertions in the main thread..!

Below is the sample code.


public void ApplicationBarWrapperTest_MenuItems_Add_New()
var waitHandle = new AutoResetEvent(false);

ApplicationBarWrapper wrapper = null;

//main thread variable to save the status.
bool isMenuItemAdded;

//child thread
Deployment.Current.Dispatcher.BeginInvoke(async () =>

wrapper = new ApplicationBarWrapper();

var newItem = new ApplicationBarWrapperMenuItem();

int menuItemsCount = wrapper.ApplicationBar.MenuItems.Count;

newItem.Text = "New Item";


//saving the status
isMenuItemAdded=wrapper.ApplicationBar.MenuItems.Count==(menuItemsCount + 1);


//back to main thread ,use that variable to throw assertion.
Assert.IsTrue(isMenuItemAdded, "Adding New Menu Item Not working");