Print Page | Close Window

Unit Testing GetEntitiesAsync

Printed From: IdeaBlade
Category: DevForce
Forum Name: DevForce Classic
Forum Discription: For .NET 2.0
URL: http://www.ideablade.com/forum/forum_posts.asp?TID=1040
Printed Date: 28-Mar-2024 at 5:48am


Topic: Unit Testing GetEntitiesAsync
Posted By: kid_kaneda
Subject: Unit Testing GetEntitiesAsync
Date Posted: 31-Dec-2008 at 3:21am
Hi
 
I'm trying to write a unit test which gets data asynchronously using GetEntitiesAsync().  When I run this under MSTest I get the following exception (including the xxx at the beginning):
 
"xxxAsync methods can only be called from applications running in a SynchronizationContext that supports thread synchronization. This means, in general, applications running in a WinForms or ASP.NET environment.  Console or WindowsService applications must use BeginInvoke and EndInvoke mechanisms instead"
 
Does this mean the async calls to the PersistenceManager cannot be tested?
 
Thanks
 
Kaneda



Replies:
Posted By: davidklitzke
Date Posted: 31-Dec-2008 at 9:11am
GetEntitiesAsynch expects to be run in an Environment where there is a main UI thread and the GetEntitiesAsynch thread is spawned by the main UI thread.  Normally, this is done by running your application as a Windows Forms Application, but the error message indicates that if you are using a Console or WindowsService application, you must use BeginInvoke and EndInvoke mechanisms instead.  Alternatively, you might might be able to write your unit test application as a Windows Forms Application.


Posted By: kimj
Date Posted: 31-Dec-2008 at 6:28pm
You can unit test async calls in MSTest or NUnit, etc, it just takes a little extra effort.  The error you see is the PersistenceManager complaining about a thread synchronization problem which you can work around.
 
The easiest, although possibly not the most robust, way to solve the problem is to set the appropriate SynchronizationContext at the beginning of your test (or in a test or class initializer), like so:
 
   SynchronizationContext sc = new System.Windows.Forms.WindowsFormsSynchronizationContext();
   System.Windows.Forms.WindowsFormsSynchronizationContext.SetSynchronizationContext(sc);
 
Once set, you can then issue async calls from your test method without the PM throwing an exception.
 
Our own unit test suite for the framework actually uses a more complex (and possibly convoluted) approach to async unit testing which involves creating a form for each test.
 
 


Posted By: kid_kaneda
Date Posted: 07-Jan-2009 at 11:51am
Thanks Kim. I'll give that a try



Print Page | Close Window