IOS Unit Test Xctest detailed

Source: Internet
Author: User
Tags new set uikit

Original blog, reprint please indicate the source
Blog.csdn.net/hello_hwc
Please pay attention to my ios-sdk detailed column
Http://blog.csdn.net/column/details/huangwenchen-ios-sdk.html

Test is an indispensable part of a good app. Each app is grouped together by a small set of features. These small functions are composed of a function or a combination of algorithms. A unit test is a test of these small functions or functions, and good unit testing can improve the robustness of your code. Xctest is a framework provided by Xcode that provides testing at all levels. Xctestcase

Each Xcode project that creates iOS has a group called "Engineering name Tests," which is a subclass of Xctestcase, and the test class in Xctest is inherited from Xctestcase.
such as a new project, named demo, you can see the figure

Take a look at what's in this automatically created file.

#import <UIKit/UIKit.h>
#import <XCTest/XCTest.h>

@interface demotests:xctestcase

@end

@implementation demotests

-(void) Setup {
    [super setUp];
    Put the setup code here. This are called before the invocation of each test method in the class.

-(void) teardown {
    //Put teardown code here. This are called after the invocation of the all test method in the class.
    [Super teardown];
}

-(void) Testexample {//This is an example of the
    a functional test case
    . Xctassert (YES, @ "pass");
}

-(void) Testperformanceexample {//This is an example of the
    a performance test case
    . [Self measureblock:^{//Put the code for you want to measure ' time of
        .}
    ]

@end
The naming of test cases

All of the test cases in Xctest are named after the tests. For example, in the above

-(void) Testexample {//This is an example of the
    a functional test case
    . Xctassert (YES, @ "pass");
}
Setup and teardown

Setup is a function that runs before all test cases run, and some common initialization work in this test case

Teardown is a xcode test Case Navigator that executes after all test cases have been completed

As with the navigation of test cases, we can run a set of test cases in the navigation of test cases, or we can run a separate test case

You can create a new set of test cases with the right mouse button.

You can also add failure breakpoints for test cases to facilitate our debugging
View Test Results

You can view the test results by testing the navigation bar

More detailed test results can be seen through the show navigation bar

Click the arrow at the back of the test case to jump to the code for the test case. Common Method Test

For example, to create a new class named model, he has this method to generate random numbers within 10.

-(Nsinteger) randomlessthanten{return
    arc4random ()%10;
}

So the test method is

-(void) testmodelfunc_randomlessthanten{
    model * model = [model alloc] init];
    Nsinteger num = [model Randomlessthanten];
    Xctassert (num<10,@ "num should less than");
}

We click on the left icon to run this test case alone, and of course it can be run separately in the navigation bar I mentioned above.

And then you see the output indicates that the test case passes

Test suite ' Selected tests ' started at 2015-06-28 05:24:56 +0000
Test Suite ' Demotests.xctest ' started at 2015-06-28 0 5:24:56 +0000
Test Suite ' demotests ' started at 2015-06-28 05:24:56 +0000
Test case '-[demotests Testmodelfunc_ra Ndomlessthanten] ' started.
Test case '-[demotests Testmodelfunc_randomlessthanten] ' passed (0.000 seconds).
Test Suite ' demotests ' passed at 2015-06-28 05:24:56 +0000.
     Executed 1 test, with 0 failures (0 unexpected) in 0.000 (0.001) seconds
Test Suite ' demotests.xctest ' passed at 2015- 06-28 05:24:56 +0000.
     Executed 1 test, with 0 failures (0 unexpected) in 0.000 (0.001) seconds
Test Suite ' Selected tests ' passed at 2015-06 -28 05:24:56 +0000.
Common Assertions

How to determine whether a test case succeeds or fails. Xctest is implemented using assertions.
The most basic assertion
Indicates that if the expression is satisfied, the test passes, otherwise the format error.

Xctassert (expression, format ...)

And a claim to direct fail.

Xctfail (Format ...)

Some of the other common assertions:

Xctasserttrue (expression, format ...)
Xctassertfalse (expression, format ...)
Xctassertequal (expression1, expression2, format ...)
Xctassertnotequal (expression1, expression2, format ...)
Xctassertequalwithaccuracy (expression1, expression2, accuracy, format ...)
Xctassertnotequalwithaccuracy (expression1, expression2, accuracy, format ...)
Xctassertnil (expression, format ...)
Xctassertnotnil (expression, format ...)
Performance Test

The so-called performance test, the main is to evaluate the running time of a piece of code, xctest performance test using the following format

For performance testing, each test case runs 10 times at a time.

-(void) Testperformanceexample {//This is an example of the
    a performance test case
    . [Self measureblock:^{//Put the code for you want to measure ' time of
        .}
    ]

For example, I'm going to evaluate a piece of code that loops print NSLog 10,000 times.
This code is as follows, and I put this code in the UIImage category.

-(void) Testperformanceexample {//This is an example of the
    a performance test case
    . [Self measureblock:^{
        for (Nsinteger index = 0; index < 10000 index + +) {
            NSLog (@ "%ld", index);
        }
        Put the code for you-want to measure ' time of.
    }];

As we all know, tests are either successful or fail, so when a key problem performance test is introduced, how to judge a performance test case is success or failure.

We'll run this test case only once, by the way we've done it earlier. Then look at the results and the output (this test case runs very slowly, don't worry)

Test case '-[modeltests Testperformanceexample] ' failed (37.432 seconds).
Test Suite ' modeltests ' failed at 2017-02-19 09:57:26.210.
     Executed 1 test, with 1 failure (0 unexpected) in 37.432 (37.433) seconds
Test Suite ' Todotests.xctest ' failed at 2017 -02-19 09:57:26.211.
     Executed 1 test, with 1 failure (0 unexpected) in 37.432 (37.434) seconds
Test Suite ' Selected tests ' failed at 2017-0 2-19 09:57:26.211.
     Executed 1 test, with 1 failure (0 unexpected) in 37.432 (37.437) seconds

test Session log:
    /users/hl/library/deve loper/xcode/deriveddata/todo-bbcdkwvzbmyznocgystdcavfakca/logs/test/98e0fa82-bacc-4361-af39-e0734f73a545/ Session-todotests-2017-02-19_095641-jm2ekf.log

Then, you will find that the test failed. This is because we have not given the performance test a reference time.
We click on the second fork arrow in the diagram

Then, seeing as figure

Let's take a look at what these parameters mean: Baseline calculates the standard deviation of the reference value Max STDD maximum allowable standard deviation at the bottom of the 1,2 ... 10 you can see the results of each run.

Click Edit, and we click on the accept on the right side of the average to set the average for this run to baseline, then Max STDD to 40%. Run this test case again and you'll find the test successful. Asynchronous Test

The logic of the asynchronous test is as follows, first defining one or more xctestexpectation to represent the desired results of the asynchronous test. The timeout is then set to indicate the maximum time that an asynchronous test can be performed. Finally, at the end of the asynchronous code completion, call Fullfill to notify the asynchronous test that the condition is met.

-(void) testasyncfunction{
    xctestexpectation * expectation = [self expectationwithdescription:@ Just a demo Expectation,should Pass "];
    Async function when finished call [expectation Fullfill]
    [self waitforexpectationswithtimeout:10 handler:^ ( Nserror *error) {
        //do something Time Out
    }];

Example

-(void) testasyncfunction{
    xctestexpectation * expectation = [self expectationwithdescription:@ Just a demo Expectation,should Pass "];
    Dispatch_async (Dispatch_get_global_queue (dispatch_queue_priority_default, 0), ^{sleep
        (1);
        NSLog (@ "Async test");
        Xctassert (yes, "should pass");
        [Expectation fulfill];
    [Self waitforexpectationswithtimeout:10 handler:^ (nserror *error) {
        //do something Time Out
    }];
}

Test results

Test suite ' Selected tests ' started at 2015-06-28 05:49:43 +0000
Test Suite ' Demotests.xctest ' started at 2015-06-28 0 5:49:43 +0000
Test Suite ' demotests ' started at 2015-06-28 05:49:43 +0000
Test case '-[demotests testasyncfunctio N] ' started.
2015-06-28 13:49:44.920 demo[2157:145428] Async test
test case '-[demotests testasyncfunction] ' passed (1.006 seconds).
Test Suite ' demotests ' passed at 2015-06-28 05:49:44 +0000.
     Executed 1 test, with 0 failures (0 unexpected) in 1.006 (1.007) seconds
Test Suite ' demotests.xctest ' passed at 2015- 06-28 05:49:44 +0000.
     Executed 1 test, with 0 failures (0 unexpected) in 1.006 (1.009) seconds
Test Suite ' Selected tests ' passed at 2015-06 -28 05:49:44 +0000.
Code Coverage

Select target and select the test module, then check gather coverage data

Then, in the show module, you can see the code coverage for each. m file.

Follow-up:

Update: 2017.02.19 to increase code coverage, detailed performance testing to explain.

The next article will explain mock tests and some common mock gadgets.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.