Xcode unit testing

前端 未结 4 1374
甜味超标
甜味超标 2020-12-02 23:56

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

4条回答
  •  囚心锁ツ
    2020-12-03 00:27

    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.

提交回复
热议问题