Xcode单元测试 [英] Xcode unit testing
问题描述
我从未使用过单元测试,我理解它的用途,但我真的不知道何时以及如何使用它。
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.
推荐答案
你几乎应该总是单元测试,你应该编写代码考虑单元测试。
极端分子甚至在编写代码之前编写测试(称为TDD - 测试驱动开发)。
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).
我会给你一个真实的例子:我最近必须编写一个支持间隔的已排序的NSArray。意思是,数组应该知道如何插入一个区间并保持它的排序。
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.
例如,数组看起来像这样:[1-3,5-9, 12-50]。在此示例中,数组中有3个区间,您可以看到它们已排序。
在我写完课程后(我称之为IntervalsArray),我 HAD 编写测试以确保它正常工作,并且如果我或其他人制作我不会破坏它将来对代码的更改。
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):
测试1:
- Create a new IntervalsArray
- Insert a new interval to the array
- (TEST) make sure the array has 1 object in it
测试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]
最后我有15个测试来覆盖我新阵列的各个方面。
At the end I had something like 15 tests to cover every aspect of my new array.
这是一个< a href =http://www.impigermobile.com/blog/introduction-to-xcode-unit-testing-in-ios/ =noreferrer>好单位 - 使用Xcode教程进行测试。
您还可以编写逻辑测试(比单元测试更复杂)来测试UI。阅读一下UIAutomation,这是Apple测试UI的方式。它并不完美,但它非常好。 这是一篇很好的教程。
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屋!