How to properly unit test calling UI method on another thread? How to properly unit test calling UI method on another thread? multithreading multithreading

How to properly unit test calling UI method on another thread?


I've been trying different things and I've come up with the following:

[Test]public void TestInvokeExWithMethodReturningResultOnOtherThread (){    // Prepare    string result = string.Empty;    var form = new Form ();    var uiThread = new Thread (() => Application.Run (form));    uiThread.SetApartmentState (ApartmentState.STA);    uiThread.Start();    Thread.Sleep (100);    var thread = new Thread (() => result = form.InvokeEx (f => f.Text));    // Execute    thread.Start ();    thread.Join ();    form.InvokeEx (f => f.Close ());    uiThread.Join ();    // Verify    Assert.That (result, Is.EqualTo ("Some label"));}

This now works perfectly.

Note that I had to add an overload for InvokeEx for a void method.