Xcode 单元测试 [英] Xcode unit testing

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

问题描述

我从未使用过单元测试,我了解它的用途,但我真的不知道何时以及如何使用它.

我想知道什么时候值得使用单元测试,也许还有一些例子.

解决方案

您几乎应该始终进行单元测试,并且编写代码时应该考虑到单元测试.极端分子甚至在编写代码之前编写测试(这称为 TDD - 测试驱动开发).

我会给你一个真实的例子:我最近不得不编写一个支持间隔"的排序 NSArray.意思是,数组应该知道如何插入一个区间并保持排序.

例如,数组看起来像这样:[1-3, 5-9, 12-50].在此示例中,数组中有 3 个间隔,正如您所见,它们已排序.在我编写完我的类(我称之为 IntervalsArray)之后,我必须编写测试以确保它正常工作,并且如果我或其他人对代码进行更改,我不会破坏"它未来.

以下是一些示例测试(伪代码):

测试 1:

- 创建一个新的 IntervalsArray- 在数组中插入一个新的区间- (TEST) 确保数组中有 1 个对象

测试 2:

- 创建一个新的 IntervalsArray- 在数组中插入 2 个区间:[1-3] 和 [5-9]- (TEST) 确保数组中有 2 个项目- (TEST) 确保区间 [1-3] 出现在区间 [5-9] 之前

最后,我进行了大约 15 个测试来涵盖我的新阵列的各个方面.

这是一个 使用 Xcode 进行单元测试的好教程.

您还可以编写逻辑测试(比单元测试更复杂)来测试您的 UI.阅读有关 UIAutomation 的一些内容,这是 Apple 测试 UI 的方式.它并不完美,但已经很不错了.这是关于此的出色教程.>

如果您认为自己是一名优秀的程序员,则应该为您的代码编写单元测试.

I have never used Unit Testing and I understand the uses of it but I don't really know when and how to use it.

I would like to know when it's worth it to use Unit Testing, maybe with some examples.

解决方案

You should almost always unit test and you should write code with unit tests in mind. The extremists write tests even before writing the code (it's called TDD - Test Driven Development).

I'll give you a real life example: I recently had to code a sorted NSArray that supports "intervals". Meaning, the array should know how to insert an interval and keep it sorted.

For example, the array would look like this: [1-3, 5-9, 12-50]. In this example there are 3 intervals in the array, and as you can see they are sorted. After I wrote my class (I called it IntervalsArray), I HAD to write tests to make sure that it works correctly and that I will not "break" it if I or someone else make changes to the code in the future.

Here are some example tests (pseudo-code):

Test 1:

- Create a new IntervalsArray
- Insert a new interval to the array
- (TEST) make sure the array has 1 object in it

Test 2:

- Create a new IntervalsArray
- Insert 2 intervals into the array: [1-3] and [5-9]
- (TEST) make sure there are 2 items in the array
- (TEST) make sure interval [1-3] comes before interval [5-9]

At the end I had something like 15 tests to cover every aspect of my new array.

Here's a good unit-testing with Xcode tutorial.

You can also write logic tests (which are more complicated than unit tests) to test your UI. Read a little about UIAutomation, which is Apple's way of testing UI. It's not perfect, but it's pretty good. Here's an excellent tutorial about this.

If you consider yourself a good programmer, you should write unit-tests for your code.

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

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