IOS unit test (Role and entry-level improvement)

Source: Internet
Author: User

IOS unit test (Role and entry-level improvement)

Because it's just something simple and practical, learning is quite good. In fact, the unit test is well used and the development will be much faster. For me, the unit test is to facilitate testing whether some functions are running normally and whether the debugging interface can be used normally. Sometimes you may want to test a network interface, restart it every time, and perform many operations before testing the network interface. If you use unit testing, you can directly test the method, which is much more convenient. For example, if we want to test whether the sharing function is normal due to many modifications, this will be useful. (Instead of restarting the program, go to the sharing page, click share, and enter the sharing content .) In fact, the unit test does not reduce the efficiency of coding. We can directly use the unit test when it passes.
Of course, there are also some advanced functions, such as automatic release and automatic testing (especially in some large projects, to prevent the program from being mistakenly modified or causing new problems ).
Now, let's clarify what the unit test has?
OCUnit (Test with XCTestIn fact, it is the test framework provided by Apple, which we mainly talk about. GHUnit is a visual testing framework. (With it, you can click the APP to decide which method to test and view the test result .) OCMock is used to simulate the return value of a method or attribute. You may wonder why you want to do this? If you use the model object generated by the model, you can transfer it in again? The answer is yes, but there are special cases. For example, if you test method A, Method B is called in method A, and method B has parameters passed in, but it is not provided by method. At this time, you can use OCMock to simulate the value returned by method B. (Simulation can be performed without affecting the test .) In addition, you can use OCMock to simulate the returned data without a network. UITests implements functions such as automatic click interface and text input through code. It is very difficult to cover all test cases by means of manual operations. Especially after the new functions are added, the old functions must be re-tested, this results in a lot of time required for regression testing. A lot of repetitive work is generated here, and some of these repetitive work can be completed automatically, at this time, UITests can help solve this problem.

Simplest unit test

1. Create a project:


2. The simplest test. Pay attention to path issues.
Enter this class, setUp is the call of each test methodBeforeRun. tearDowLICEcapn calls each test method.AfterRun. TestExample is the test method, which is no different from what we created. However, the test method must be in the format of testXXX and cannot contain parameters. Otherwise, it will not be recognized as a test method. The execution sequence of the test method is lexicographically ordered.
Press the shortcut key Command + U to perform unit test. This shortcut key is for all tests.
Input in testExample Method

NSLog (@ "Custom test testExample"); int a = 3; XCTAssertTrue (a = 0, "a cannot be equal to 0 ");

Click the play button to start testing a single method:


The following result is displayed. We assert that a cannot be equal to 0, so the test fails. Of course there are other things, which can be used again and all in the demo.

Test network requests

Install AFNetworking and STAlertView using CocoaPods (CocoaPods installation and usage tutorial)
Pofile:

platform :ios, '7.0'pod 'AFNetworking', '~> 2.5.0'pod 'STAlertView', '~> 1.0.0'

AFNetworking cannot be used in unit test at all. Because no library is found, we need to configure the following:



Add the NSAppTransportSecurity type Dictionary to Info. plist. Add the NSAllowsArbitraryLoads type Boolean under NSAppTransportSecurity and set the value to YES. The settings are as follows:

Http security problem of iOS9: Now the Network Test of asynchronous requests will end after the main thread of the test method is executed, so you need to set it up. Otherwise, you cannot view the asynchronous return result. Set the wait before the method ends. When the method is called back, let it continue. The macro definition is as follows:

// WaitForExpectationsWithTimeout is the waiting time. If it exceeds the waiting time, it will not wait for execution. # Define WAIT do {\ [self expectationForNotification: @ "RSBaseTest" object: nil handler: nil]; \ [self waitForExpectationsWithTimeout: 30 handler: nil]; \\} while (0) # define NOTIFY \ [[nsicationcenter center defacenter center] postNotificationName: @ "RSBaseTest" object: nil]

Added the test method testRequest:

-(Void) testRequest {// 1. request manager AFHTTPRequestOperationManager * mgr = [AFHTTPRequestOperationManager manager]; mgr. responseSerializer. acceptableContentTypes = [NSSet setWithObjects: @ "text/html", nil]; // 2. send GET request [mgr GET: @ "http://www.weather.com.cn/adat/sk/101110101.html" parameters: nil success: ^ (AFHTTPRequestOperation * operation, id responseObject) {NSLog (@ "responseObject: % @", responseObject ); XCTAssertNotNil (responseObject, @ "error returned"); y // continue execution} failure: ^ (AFHTTPRequestOperation * operation, NSError * error) {NSLog (@ "error: % @", error); XCTAssertNil (error, @ "request error"); y // continue execution}]; WAIT // pause}

Sometimes we want to test whether the entire process can run through, such as obtaining verification codes, logging on, uploading portraits, and querying personal data. In fact, you only need to enter the verification code to complete the test. In this case, the input box is used for the program to continue execution. Use a third-party pop-up input box STAlertView, which has been set previously.
STAlertView usage:

Self. stAlertView = [[STAlertView alloc] initWithTitle: @ "Verification Code" message: nil textFieldHint: @ "Enter the phone verification code" textFieldValue: nil cancelButtonTitle: @ "cancel" otherButtonTitle: @ "OK" cancelButtonBlock: ^ {// click Cancel to return and execute [self testAlertViewCancel]; NOTIFY // continue execution} otherButtonBlock: ^ (NSString * B) {// click OK and then run [self alertViewComfirm: B]; y // continue execution}]; [self. stAlertView show];
For advanced automated unit testing, we recommend that you view the demonstration github of LeanCloud engineer Li Zhiwei's live video of Automated Unit Testing
In fact, it is very good. We have talked about automated unit testing and automated release. However, due to your insufficient skill, you can only keep learning later.

Demo download: UnitTestDemoTests

 

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.