I have the following situation in my unit tests using Moq on .NET 4.0 using Microsoft BCL
Task<MyClass> mockTask = new Task<MyClass>(() => new MyClass());
uploadHelper.Setup().Returns(mockTask);
Task.WaitAll(mockTask);
The problem that I am facing is that Task.WaitAll(mockTask) simply blocks and never returns.
What am I doing wrong here?
Edit Note that mockTask is async here in my context.
Your task is not started !
Just use:
Task<MyClass> mockTask = Task.FromResult(new MyClass());
Alternatively, this works as well:
Task<MyClass> mockTask = new Task<MyClass>(() => new MyClass());
mockTask.Start();
The proposed solutions have one problem - the task may be over by the time Returns
is called.
That means your unit test exhibits a different async semantics than your real code. Is that what you want?
If you truly want to capture the async nature of the tested code you must not use the Returns
method with a value.
Instead use the Returns overload accepting a function. Something like this:
uploadHelper.Setup().Returns(() => Task.Run(() => new MyClass()));
That way you can be certain to exercise async execution path.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With