I'm facing an issue that I do not understand when unit testing a code that uses task continuation and DispatcherSynchrinizationContext.
My unit test code :
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext());
var class1 = new Class1();
var result = class1.MyAsyncMethod().Result;
Assert.IsTrue(result == "OK");
}
}
The code that is being tested :
class Class1
{
public Task<string> MyAsyncMethod()
{
var tcs = new TaskCompletionSource<string>();
MyInnerAsyncMethod()
.ContinueWith(t =>
{
// Never reached if TaskScheduler.FromCurrentSynchronizationContext() is set
tcs.SetResult("OK");
}, TaskScheduler.FromCurrentSynchronizationContext());
return tcs.Task;
}
private Task<string> MyInnerAsyncMethod()
{
var tcs = new TaskCompletionSource<string>();
tcs.SetResult("OK");
return tcs.Task;
}
}
The problem is that the code contained within the "ContinueWith" method is never reached IF I specify "TaskScheduler.FromCurrentSynchronizationContext()". If I remove this parameter, the continuation executes correctly ...
Any ideas or advices?