unit testing asynchronous operation

前端 未结 4 579
名媛妹妹
名媛妹妹 2021-02-13 11:41

I want to unit test a method that I have that performs and async operation:

 Task.Factory.StartNew(() =>
        {
            // method to test and return v         


        
4条回答
  •  时光取名叫无心
    2021-02-13 12:36

    You'd have to have some way of faking out the task creation.

    If you moved the Task.Factory.StartNew call to some dependency (ILongRunningOperationStarter) then you could create an alternative implementation which used TaskCompletionSource to create tasks which complete exactly where you want them to.

    It can get a bit hairy, but it can be done. I blogged about this a while ago - unit testing a method which received tasks to start with, which of course made things easier. It's in the context of async/await in C# 5, but the same principles apply.

    If you don't want to fake out the whole of the task creation, you could replace the task factory, and control the timing that way - but I suspect that would be even hairier, to be honest.

提交回复
热议问题