iOS Unit testing (action and Getting started)

Source: Internet
Author: User

Because it is just some simple and practical things, learning is very good. In fact, unit testing is good, the development will be much faster. Unit testing for me, for the time being, is to make it easy to test whether some of the features are working properly, and whether the debug interface is working properly. Sometimes you might be trying to test a network interface, and then it restarts every time and after a lot of action, you test that network interface. If you use unit tests, you can test that method directly, which is relatively convenient. For example, because of many changes, we would like to test the sharing function is normal, this time it is useful. (instead of restarting the program, go to the sharing screen, tap share, fill in the share.) In fact, unit testing does not reduce the efficiency of our code, we can pass the unit test, directly to the appropriate place.
Of course there are some high-level roles, such as auto-release, automated testing (especially in some big projects, to prevent programs from being mistakenly altered or causing new problems).
Now, let's start with the unit test.
ocunit( 即用XCTest进行测试 ) is actually the test framework that Apple comes with, and that's what we're mainly talking about. Ghunit is a visual testing framework. (with it, you can click on the app to decide which method to test, and you can click to view the test results.) Ocmock is to simulate the return value of a method or property, and you may wonder why you should do so? Using Model objects generated by models, and then passing them in? The answer is yes, but there is a special case. For example, you are testing method A, method A is called to Method B, and Method B is a parameter passed in, but it is not provided by method A. At this point, you can use Ocmock to simulate the value returned by Method B. (This can be simulated without affecting the test.) In addition to these, data returned by Ocmock can be simulated without a network. Uitests is through the code to achieve automatic click Interface, input text and other functions. It is very difficult to cover all the test cases in a manual manner, especially after adding new features, and the old functionality will have to be re-tested, which results in a lot of time for the tests to be performed, and there is a great deal of repetitive work, and some of these repetitive tasks can be done automatically. At this time uitests can help solve this problem.

The simplest unit test

1. New Project:


18ca997f-4911-4b99-9a83-2ab44a77e8e8.png


2. The simplest test, pay attention to the problem of the path
Into this class, Setup is executed before each test method call, and TEARDOWLICECAPN is executed after each test method call. Testexample is a test method, and there is no difference between our new ones. However, the test method must be in a testxxx format and cannot have parameters, otherwise it will not be recognized as a test method. The order in which the test methods are executed is dictionary ordered.
Press the shortcut key command + U for unit testing, this shortcut is all tested.
In the Testexample method, enter

    NSLog(@"自定义测试testExample");    int  3;    XCTAssertTrue(a == 0,"a 不能等于 0");

Click the Play button to start a single method test:


8f503aa4-c630-419a-9f66-c779c81a5581.png


As a result, the test fails because we assert that a is not equal to 0. Of course there are other, used to see, the demo has.


8bad5cd6-7fb7-4626-a1f8-cbc2b6b35e89.png Testing for network requests

Installing afnetworking and Stalertview with Cocoapods (cocoapods installation and use tutorial)
Pofile:

:ios‘7.0‘‘AFNetworking‘‘~> 2.5.0‘‘STAlertView‘‘~> 1.0.0‘

At this point we will find that afnetworking is not available in the unit test because the library is not found, so we need to configure:


Uitestdemo setting. gif
Uitestdemo setting 2.gif


Add the Nsapptransportsecurity type dictionary in Info.plist. Under Nsapptransportsecurity, add the Nsallowsarbitraryloads type Boolean with the value set to Yes. Set the location as follows:


A0f7275a-d79d-4da4-955b-8bfe862d10e4.png

IOS9 HTTP Security issue: The network test for asynchronous requests now, because the test method is finished executing the main thread, you need to set up, otherwise you can not view the asynchronous return results. Set the wait before the end of the method and let it continue when you return. (another unit test for an asynchronous function) defines a macro as follows:

//waitForExpectationsWithTimeout是等待时间,超过了就不再等待往下执行。#define WAIT do {\\    [self expectationForNotification:@"RSBaseTest" object:nil handler:nil];\    [self waitForExpectationsWithTimeout:30 handler:nilwhile (0)#define NOTIFY \\[[NSNotificationCenter defaultCenter]postNotificationName:@"RSBaseTest" object:nil]

Add test method Testrequest:

-(void) testrequest{//1. GET Request ManagerAfhttprequestoperationmanager *mgr = [Afhttprequestoperationmanager manager]; Mgr. Responseserializer. Acceptablecontenttypes= [NssetSetwithobjects:@ "text/html",Nil];//2. Send a GET request[Mgr GET:@ "http://www.weather.com.cn/adat/sk/101110101.html"ParametersNilsuccess:^ (Afhttprequestoperation *operation,IDResponseobject) {NSLog(@ "responseobject:%@", Responseobject); Xctassertnotnil (Responseobject,@ "Error returned"); NOTIFY//Continue execution} failure:^ (Afhttprequestoperation *operation,Nserror*error) {NSLog(@ "error:%@", error); Xctassertnil (Error,@ "Request Error"); NOTIFY//Continue execution}]; WAIT//Pause}

Sometimes we want to test whether the whole process can run through, such as Get verification code, login, upload avatar, query personal data. In fact, just enter the verification code to complete the test. The input box needs to be used so that the program can continue to execute. Use a third-party pop-up input box Stalertview, which has been set up earlier.
How to use Stalertview:

         Self. Stalertview= [[Stalertview alloc]initwithtitle:@ "Verification Code"MessageNilTextfieldhint:@ "Please enter your phone verification code"Textfieldvalue:NilCancelbuttontitle:@ "Cancel"Otherbuttontitle:@ "OK"cancelbuttonblock:^{//Click Cancel to go back and execute[ SelfTestalertviewcancel]; NOTIFY//Continue execution} otherbuttonblock:^ (NSString*B) {//Click OK to execute[ SelfALERTVIEWCOMFIRM:B]; NOTIFY//Continue execution}]; [ Self. StalertviewShow];
    • Advanced Automated unit testing, recommended to see live video of Leancloud Engineer's Li Zhiwi automated Unit Test
    • Li Zhiwi's demo GitHub
      In fact, it is very good, automated unit testing, automatic release has been talked about, but because of their own skill is not enough, can only keep the later study slowly.

Demo Demo Download: unittestdemotests




    iOS Unit testing (action and Getting started)

    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.