Unit testing gotcha

In the course of writing unit tests on a project, I came across in interesting wrinkle for testing MVVMLight ViewModel classes. When creating a ViewModel, the work is actually done on different thread which leads to the following unit test code throwing an exception.

Instantiating the SummaryViewModel class leads to the following exception message being displayed.

The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))

The solution is relatively simple, though. First I create a method to allow me to run an action and marshal its result back to the appropriate thread.

And then I created a method specifically to create the SummaryViewModel, since I will be doing that many times across my unit tests.

Then it is just a matter of changing my test method to call CreateViewModel and await the result, and all is good.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">