IOS Unit Test-Xcode 7 test Tool Xctest Learning

Source: Internet
Author: User

1. Unit Test Introduction 1.1, Unit testing: Unit Test

The word test is easy to understand, so what is a unit?

A unit refers to the smallest unit that can be tested in an application.

A set of source code can be tested, generally require a clear input and output. Therefore, in general the source code explicitly contains the input and output of each method is considered a test unit (a case).

Note that the output here is not limited to changes in the input parameters of the method's return value, but also any data that the method changes during execution.

Unit testing in the program can understand a module of a method, in each of the possible modules are tested to ensure that each module is not a problem, thereby improving the overall quality of the program.

1.2, the purpose of unit testing

The purpose of unit testing is to isolate all the source code in the program into the smallest testable unit, to ensure the correctness of each unit, and to ensure that the overall application is fairly accurate if each unit is guaranteed to be correct. On the other hand, the test script itself is the actual code used to test the code, which is helpful for the developer to understand the use of the unit being tested.

Test is a black box test and white box test (the concept is not explained here), unit testing is actually a white box test, the developer of the existing implementation of the module to write their own test script to test, which also contains the design of test cases. In contrast, white-box testing is done by the developer themselves, and then tested in black box by the Test team, which also helps improve the integrity of the test process and ultimately the quality of the product.

Content of unit tests:

    • Test purposes for unit tests
    • Module Interface Test
    • Local Data structure Testing
    • Path testing
    • Error handling Test
    • Boundary test

In the existing development work, we generally ignore the importance of unit testing, the development of the function after the developer to get the existing test cases, directly for each use case for manual testing, testing through the test, then the test staff repeat the process of manual testing, data mock, special test, etc. So since the white box testing process has a very low time and weight, developers do not know their module code coverage problem, more time may be some code until the line has never run, so that in the real environment will produce some unexpected problems, so the risk is very high, Unit testing is also critical in general.

Here are some of the testing tools available in Xcode7:

2. Introduction of UnitTest2.1 and Xctest in Xcode7

This paper mainly Xcode7 to explain.

The latest Xcode7 contains the UITest unittest tool, which can be selected at the time you create the project, or it can be done directly in the form of Addtarget,

2.1, Xctestcase Introduction

If the project was created with a tick of unittest (from the name of the official Apple Unit Test tool), we can see that there is a more directory in the project, and one more class by default.

Select Xctest:

Xctest when Apple officially provided a test tool, a built-in testing framework, from the project can be seen, a "application name" group, we can directly use Commond+r to travel, a test target we can use commond+ U come to the test target, there will be a default "application name" +test class in the target directory, this class only. m does not have. h, inherited from Xctestcase, and can be run using Commond+u.

The default test class has the following methods:

//方法在XCTestCase的测试方法调用之前调用,可以在测试之前创建在test case方法中需要用到的一些对象等- (void)setUp ;//当测试全部结束之后调用tearDown方法,法则在全部的test case执行结束之后清理测试现场,释放资源删除不用的对象等- (void)tearDown ;//测试代码执行性能- (void)testPerformanceExample
2.2, Xctestcase use

Xctestcase initialization is not user-controlled, and developers do not need to manually alloc, init, or invoke static method initialization for Xctestcase subclass, for unit testing of a function block (for a class) Just to create a separate for this class to inherit from Xctestcase, after implementing the basic functions in this file (half the system will default to create these three functions), in fact, the logic only requires the developer to define a function that begins with "test", then internally implement their own for a function, A test script that returns numeric results, operations, and so on, commond+u the execution time, the unit test automatically executes the function that starts with the test, and when a blue mark appears on the function head, it indicates that the tests pass, otherwise the red error is reported directly.

Xctest Test Category:

    • Basic Logic Test processing test
    • Load data test asynchronously
    • Data Mock Test
Xctest Common Basic test tools

Some of the xctest commonly used for judging tools are xct, such as:

  //Assert, most basic test, if expression is true then pass, otherwise print after formatting stringXctassert (expression,format...)//bool Test:Xctasserttrue (expression,format...) Xctassertfalse (expression,format...)//Equality testXctassertequal (expression1, Expression2,format...) Xctassertnotequal (expression1, Expression2,format...)//double float vs. data test usingXctassertequalwithaccuracy (expression1, expression2, accuracy,format...) Xctassertnotequalwithaccuracy (expression1, expression2, accuracy,format...)//nil test, Xctassert[not]nil assertion determines whether the given expression value is nilXctassertnil (expression,format...) Xctassertnotnil (expression,format...)//Failure AssertionXctfail (format...)
Xctest Asynchronous Test

Perhaps the most exciting feature added to the Xcode unit test is the asynchronous test that the class Xctestexpression class brings in. Now the test can wait for a specified length of time, until certain conditions are met when the test starts. Without having to write a lot of GCD code control.

To use asynchronous testing, first create a expection with method expectationwithdescription

let expectation = expectationWithDescription("...")

After that, at the end of the method, add method Waitforexpectationswithtimeout, specifying the time to wait and the closure to execute if the condition is not met in the specified time.

waitForExpectationsWithTimeout(10in    ...}

The rest is to tell the expectation condition to be satisfied in the rest of the async test's callback function.

expectation.fulfill()

If there are multiple expectation in the test, each expectation must be fulfill, otherwise the test will not pass.

-(void) testfetchrequestwithmockedmanagedobjectcontext{mocknsmanagedobjectcontext *mockcontext = [[ Mocknsmanagedobjectcontext Alloc] Initwithconcurrencytype:0x00]; Let Mockcontext = Mocknsmanagedobjectcontext () nsfetchrequest * fetchrequest = [[Nsfetchrequest alloc] InitWithEntityNa me:@"User"]; Let fetchrequest = Nsfetchrequest (entityname:"User") Fetchrequest.predicate = [Nspredicate predicatewithformat:@"email ENDSWITH[CD] apple.com"]; Fetchrequest.predicate = nspredicate (format:"email ENDSWITH[CD]%@","Apple.com") Fetchrequest.resulttype = Nsdictionaryresulttype; Fetchrequest.resulttype = nsfetchrequestresulttype.dictionaryresulttype varError: Nserror? Nserror *Error= nil; Nsarray *results = [Mockcontext executefetchrequest:fetchrequestError:&Error]; Let results = Mockcontext.executefetchrequest (Fetchrequest,Error: &Error) Xctassertnil (Error, @"error should be nil"); Xctassertequal (results.Count,2, @"Fetch request should return only one structure"); Nsdictionary *result= results[0]; Xctassertequal (result[@"Name"], @"Zhang San", @"name should be Zhang San"); NSLog (@"Email:%@",result[@"Email"]); Xctassertequal (result[@"Email"], @"[email protected]", @"email should be [email protected]");}
Xctest Mock

Data mock

2.3, Xcode7 Code Coverage Introduction

Code coverage, so the name of the code coverage = Actual execution of the number of lines of code/the total number of lines of engineering code, straightforward speaking is such a value, discussed above, the purpose of unit testing in addition to the program is divided into the smallest unit independent to test to ensure that the correct, there is a code coverage problem, If there is a good part of the code sent to the line has never been executed, the problem is quite dangerous (the problem can be speculated on their own, believe that the problem is not very strange).

The Code Coverage tool uses

Xcode7 provides a built-in code coverage tool component, nonsense not to say, see below how to use:

1, first need to Product->scheme->edit scheme inside the Code coverage mode open, check for debug mode,:

Edit Scheme:

2, open Code Coverage mode, open a test class, commond+u run, if the test passed, the test script will appear on the function header a green flag (instead of how to test which method does not pass, will prompt a red error), as follows:

3. Open the report Navigator of the left window of Xcode, find Project log, select the last Log option, the last one is a test log, select the log instance, and you can see the interface,
:

Then check the coverage in the tab, and you can see the approximate code execution coverage, and if the indicator bar is full, run it all over again on behalf of that class of code.

4. Double-click the class you want to view, select View Uatrackdao here, open to see what code has been executed in the test just now, the code is not executed, the Orange representative has not executed, Each line that executes is followed by an ordinal number that represents how many times this line of code was executed during the test that was just taken. If there are any, you can adjust the corresponding test script according to the specific situation, continue the test, and finally ensure that each line of code is executed correctly:

3. Introduction to Uitestunittest in Xcode7

In any software development, automated UI testing is important (the benefits of UI Automation testing are no longer mentioned here), and the iOS platform used to do automated UI testing through UIAutomation, and its test cases are written in JavaScript ( Instruments in this function), this process is very cumbersome, it is necessary to write the corresponding test script, slow, high learning costs (about Automation Automation test concept You can view the relevant information, automation automated testing on all major platforms have applications, In the large-scale software development testing process indeed can save a lot of manual testers, greatly improve the cost and efficiency of software testing, in the latest Xcode7 this article recommended the use of Apple's latest tool uitest).

Apple has added unittest to Xcode 6, and to Xcode 7 Apple has provided a new framework uitest, which is primarily used to test the UI, unittest to test the functional logic code, and UITest is designed to test the UI.

Xcode 7 has integrated uitest,uitest allows you to find and interact with UI elements, as well as check the properties and status of the UI, and UITest has been integrated with Xcode's test reports, which can be executed with unit tests. As with UnitTest, we can perform assertions at the time the UI is checked.

Creating a UITest target will also generate a "project name" +uitest the group,uitest target can be checked at the time the project was created, or it can be added manually in the project, under the "project name" +uitest Group, We can see that the system will help us generate a UI test class by default, and this class is also inherited from Xctestcase. This shows that both unit tests and UI tests in iOS are based on xctestcase.

UnitTest UI Test

To create a modal view, we choose to push from the first VC to the second VC by clicking the button

To create the UITest target, we test the above UI with the options:

Open UATRACKDEMOUITEST.M

Create-(void) Testui, while leaving the cursor inside the function

Click on the red button below to start the recorder operation, after the program runs, click on the interface button, the program will push to a new page, this time will see the mouse cursor at the moment to automatically generate a part of the code, repeated operations, each time will generate new code,

From the new Click the Little Red dot button, at this time to end the recorder operation, Commond+u run the test, at this time, a series of actions will be carried out in succession:

Declare here: First click on the Red Recorder button, then manual action will automatically generate a test script, the second time commond+u is to test the UI.

Xctest UI Testing API

Before we start recording an action, we have to decide what we need to assert. We can use the Xctest framework to assert some of the content in the UI, and now the framework already contains the following three new APIs.

    • Xcuiapplication. This is the agent for the app you're testing. It allows you to launch the app so you can perform the test. It will be a new process each time, it will take a little more time, but to ensure that the test application state is clean, so you need to deal with a few variables.

    • Xcuielement. This is the proxy for the UI element in the app you are testing. Each element has a type and identifier, which in combination can find the UI elements in the app. All of the elements are nested in the tree that represents your app.

    • Xcuielementquery. When you want to find an element, you use element query. Each of the xcuielement contains a query. These query search xcuielement trees and must find a match. Otherwise, the test fails when your view accesses the element. The exception is the Exists property, which you can use to check whether an element is present in the tree. This is useful for assertions. More generally, you can use Xcuielementquery to find elements that are visible to accessibility. Query returns a collection of results.

Now that you can run the test using the CLI without further tweaking, but we want the UI tests in a separate scheme, click Scheme and select New scheme:

Select the newly created UI Test Target and confirm.

If you plan to run tests on Ci-server, make sure that the most recently created scheme has the shared option enabled. Click Scheme and select Manage schemes to open the session.

To open a test from the CLI
xcodebuild -workspace App.xcworkspace    -scheme "SchemeName"            -sdk iphonesimulator            -destination ‘platform=iOS Simulator,name=iPhone 6sp,OS=10.0‘           test

It is important to make it clear that the version of Xcode is in use, and we are using the latest beta version:

export DEVELOPER_DIR="/Applications/Xcode-beta.app"

You can even use the beta version as your new default running version:

sudo xcode-select --switch"/Applications/Xcode-beta.app"
Generated

No additional work is required and can be easily obtained with light. You can add the Deriveddatapath option to the command, and tell Xcode where to store the test results, including the generated.

xcodebuild -workspace App.xcworkspace    -scheme "SchemeName"            -sdk iphonesimulator            -destination ‘platform=iOS Simulator,name=iPhone 6sp,OS=10.0‘           -derivedDataPath ‘./output‘           test
UnitTest Tool Development

Xctest provides a total of three UI test objects

    • Xcuiapplication Current test application target
    • Xcuielementquery locating a class that queries Xctuielement in the current UI
    • Xcuielement any item item in the UI test is abstracted into a xcuielement type

When we get the recorded generated code, based on the three kinds of objects provided by UITest, I can modify and debug the test code here.

The following assertions are also applicable in UITest:

Xctassert (expression,format...)//bool Test:Xctasserttrue (expression,format...) Xctassertfalse (expression,format...)//Equality testXctassertequal (expression1, Expression2,format...) Xctassertnotequal (expression1, Expression2,format...)//double float vs. data test usingXctassertequalwithaccuracy (expression1, expression2, accuracy,format...) Xctassertnotequalwithaccuracy (expression1, expression2, accuracy,format...)//nil test, Xctassert[not]nil assertion determines whether the given expression value is nilXctassertnil (expression,format...) Xctassertnotnil (expression,format...)//Failure AssertionXctfail (format...) .....

About Xcode 7 UnitTest The problem is here, I hope that interested students all share ...

4. Summary 1. Summarize existing issues and share insights

Xcode7 's built-in tools are finally good enough. This means that even large apps do not necessarily exclude Xcode's built-in testing tools for code coverage of unit tests. Whatever the test, Xctest's assertions, expectation, and performance tests are adequate. But no matter how good the tool is, it needs to be done.

If you're testing an iOS or OS X app, start adding some assertions to the automatically added test class and press Command+u. You will surely find that these tools make your test a lot easier.

IOS Unit Test-Xcode 7 test Tool Xctest Learning

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.