单元测试异步操作 [英] unit testing asynchronous operation

查看:131
本文介绍了单元测试异步操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要进行单元测试,我有一个方法,执行和异步操作:

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

 Task.Factory.StartNew(() =>
        {
            // method to test and return value
            var result = LongRunningOperation();
        });

我存根必要的方法等在我的单元测试(C#编写的),但问题是,我才断言测试异步操作尚未完成。

I stub the necessary methods etc in my unit test (written in c#) but the problem is that the async operation is not finished before I assert the test.

我怎样才能解决这个问题?我应该创建TaskFactory或任何其他提示,以单位的模拟测试一个异步操作?

How can I get around this? Should I create a mock of the TaskFactory or any other tips to unit testing an async operation?

推荐答案

您得有伪​​造出来的任务创建的一些方法。

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

如果您移动 Task.Factory.StartNew 调用一些依赖( ILongRunningOperationStarter ),那么你可以创建一个它使用的另一种实现 TaskCompletionSource 以创建任务,正是你希望他们到完整的。

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.

它可以得到一个有点毛茸茸的,但它的可以的完成。我blogged这个的前一阵子 - 单元测试它的的方法获得的任务下手,这当然使事情更加容易。这是在异步的/等待在C#5的范围内,但同样的原理也适用。

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.

这篇关于单元测试异步操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆