tags:

views:

178

answers:

4

I am trying to write a test case where I have to access UI Thread. Does Nunit provide a way to access the ui thread or is there anyway I can execute some code on UI Thread in my test case. Thanks

Update: I'm using winform. The usual way is to have the presentation layer and write the test cases against it but in this situation I have a grid that I need to work with and to populate it, its DataSource property needs to be set on UI Thread.

+3  A: 

That very much depends on which technology you are using for your UI. Depending on that it might be possible to setup the NUnit runner thread to act as your UI thread.

Genrally though, it is recommended to make the actual UI layer as thin as possible to reduce the amount of UI-code to test.


If you really need to have a live WinForms control on your NUnit thread, consider using Application.DoEvents() which will handle all currently pending events in the message queue. Be aware that doing so might bring you other problems though.

David Schmitt
David I totally agree but the situation I have doesn't leave me any options. I have infragistic grid (wingrid) that I'm working on and I need to get filters. To do that, I need to pupulate it(grid.Datasource = data). Grid doesn't populate itself unless it's being executed on UI Thread. Technology I'm using is Win forms
Sheraz
A: 

NUnit has no builtin support AFAIK. You can execute code in your UI thread of course, but the 'how' depends on the UI technology you use (WPF or Winforms)

Look for something like BeginInvoke() and pass an anonymous delegate to it that you can define in your unit test

chris166
http://weblogs.asp.net/justin_rogers/pages/126345.aspx
slf
to my understanding, BeginInvoke will invoke the passed delegate on the thread it was instantiated on. IF I create a control on non ui thread then it will not exectue it on UI thread. Please correct me if I'm wrong.
Sheraz
No it will always run on the UI thread (e.g. the one that executes Application.Run for Winforms)
chris166
+2  A: 

You could try NUnit Forms, but I'd second David's recommendation to take as much logic as possible out of the UI layer.

Chris Doggett
A: 

There is a 'RequiresSTA' attribute you can specify on the test that will run it in the same thread as the NUnit UI.

I discovered this when trying to write a test for a TIBCO Rendezvous message. The listener has to be set up in the main UI thread (blame TIBCO, not me!), otherwise the call to getAutoDispatchQueueGroup returns an error "Object cannot complete the requested operation".

I tried using WindowsFormsSynchronizationContext and BeginInvoke, and neither worked.

DavidB