TDD:单元测试异步调用 [英] TDD: Unit Testing Asynchronous Calls

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

问题描述

人:

我正在开发一个应用程序,并通过单元测试对其进行构建.

I'm working on an application, and building it with unit testing.

但是,我现在处于需要测试异步调用的情况. 例如

However, I'm now in a situation where I need to test asynchronous calls. For example,

- (void)testUserInfoBecomesValidWhenUserIsBuiltSuccessfully
{
    if ( ![userBuilder userInfoUpToDate] )
    {
        [userBuilder buildUser];
    }

    STAssertTrue([userBuilder userInfoUpToDate], @"User information is not valid before building the user");
}

测试此类事物的一般做法是什么? 预计userInfoUpToDate将异步更新.

What is the general practice for testing such things? userInfoUpToDate is expected to be updated asynchronously.

谢谢! 威廉

推荐答案

有时候,有些东西很容易被人们用来测试您通常不使用单元测试来测试的东西.这主要是由于误解和渴望测试一切的缘故.然后您意识到您不知道如何使用单元测试进行测试.

Sometimes there is a temptation to test things which you don't usually test using Unit Testing. This basically comes from misunderstanding and desire to test everything. And then you realize you don't know how to test it with unit-testing.

您最好问自己-我在这里测试什么?

You would better ask yourself - what do I test here?

我是否测试直到请求完成才提供数据?

Do I test that the data is not available until request completes?

然后,您可以编写测试的非异步版本,该版本将在请求完成后检查数据是否可用.

Then you can write non-async version of the test which will check that the data is available after request completes.

我是否可以根据要求测试响应是否正确保存?

Do I test that the response saved correctly after request?

您也可以使用逻辑中的标志对其进行测试.

You can also test it using flags in your logic.

您可以执行所有逻辑测试,而无需运行异步测试.

You can do all logic tests without running asynchronous tests.

所以在底部,我什至会问你为什么认为需要测试异步呼叫?

So at the bottom I would even ask you why do you think you need to test async call?

单元测试应该可以快速运行-因此将其视为不测试异步调用的另一个原因.想象一下运行这些测试的连续集成系统-这将需要额外的时间.

The unit tests supposed to run quickly - so consider it as another reason to not test async calls. Imagine continuous integration system which runs these test - it will need extra time.

然后阅读您对其他答案的评论-我认为在测试中完全不使用异步.例如. TDD书中的肯特·贝克(Kent Beck).提到可以进行并发单元测试,但这种情况很少见.

And reading your comments to another answer - I think it's not common to use async in testing at all. E.g. Kent Beck in TDD book. mentioned that Concurrent Unit Testing is possible but very rare case.

那么-什么&为什么您真的要测试?

So - what & why you really want to test?

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

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