lain you put me on the right way, thank you !!
I did not modify my code being tested and here is a new implementation of the test code that works as expected :
[TestClass]
public class UnitTest1
{
private ExecutionContext _executionContext;
[TestInitialize]
public void OnSetup()
{
_executionContext = CreateExecutionContext();
SynchronizationContext.SetSynchronizationContext(_executionContext.DispatcherSynchronizationContext);
}
[TestCleanup]
public void OnTearDown()
{
// stops the dispatcher loop
_executionContext.Dispatcher.InvokeShutdown();
}
[TestMethod]
public void TestMethod1()
{
var class1 = new Class1();
var result = class1.MyAsyncMethod().Result;
Assert.IsTrue(result == "OK");
}
/* Helper classes and methods */
private ExecutionContext CreateExecutionContext()
{
var tcs = new TaskCompletionSource<ExecutionContext>();
var mockUIThread = new Thread(() =>
{
// Create the context, and install it:
var dispatcher = Dispatcher.CurrentDispatcher;
var syncContext = new DispatcherSynchronizationContext(dispatcher);
SynchronizationContext.SetSynchronizationContext(syncContext);
tcs.SetResult(new ExecutionContext
{
DispatcherSynchronizationContext = syncContext,
Dispatcher = dispatcher
});
// Start the Dispatcher Processing
Dispatcher.Run();
});
mockUIThread.SetApartmentState(ApartmentState.STA);
mockUIThread.Start();
return tcs.Task.Result;
}
internal class ExecutionContext
{
public DispatcherSynchronizationContext DispatcherSynchronizationContext { get; set; }
public Dispatcher Dispatcher { get; set; }
}
/* ------ */
}