Xcode 7 intelligent test tool XCTestCase learning


  • Layout: post
  • Title: Xcode 7 intelligent test tool XCTest learning”
  • Subtitle: Xcode 7 intelligent test tool XCTest learning”
  • Date: 2015-11-6
  • Author: “Scenery” tags: iOS iOS UI test unit testing XCTestCase e-commerce in

Xcode 7 intelligent test tool XCTest learning

1 unit test profile

1.1, Unit Testing: unit test

Testing the word is easy to understand, so what is the unit (Unit)? A unit is 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. So in general, each of the methods in the source code that explicitly contains the input and output is considered a test unit (a case). Note that the output here is not limited to changes in the input value of the return value of the method, as well as any data that the method changes during execution.

Unit testing in the program can understand a module a method, in each of the modules can be tested, to ensure that each module is no problem, so as to improve the quality of the overall program.

1.2, the purpose of unit testing

The purpose of unit testing is all the source code procedures, can be separated into the smallest unit of testing, to ensure the accuracy of each unit, if each unit can ensure the correct, can guarantee the correctness of the overall application level. On the other hand, the test script itself is the actual use of the test code, which is helpful for the developer to understand the use of the test unit.

The test is divided into white box and black box testing (concept here is not in the interpretation), unit testing is a white box testing, has been implemented on the existing module developers write the corresponding test scripts for testing, this design also includes test case. Relatively speaking, the developers themselves to complete the white box test, and then handed over to the test team for black box testing, which is also more conducive to improving the integrity of the testing process, and ultimately improve the quality of the product.

Unit test content:

Unit testing test purpose module interface test local data structure test path test error test test boundary test

In the existing development work, we will generally ignore the importance of unit testing, functional development after the completion of the developers to get the current test case, manual test directly for each test case, is provided by measurement, test personnel or repeated manual testing process, data mock, special test, so since the white box testing process time weight will become very low, developers do not know their own problems covered road module code, more time may be some code until the line never run before, that will produce some unexpected problems in real environment, so the risk is very high, the whole unit the test is essential.

Here are some of the existing test tools in Xcode7:

2 Xcode7 in UnitTest

2.1, XCTest introduction

In this paper, the basic Xcode7 to explain, as for the history of the new features of Xcode to go to their own, here only to explain how to use, nonsense less, directly into the following topics.

The latest Xcode7 is included in the UITest UnitTest tool, which can be created in the time you choose the corresponding option, you can also directly through the form of addTarget to complete,

2.1, XCTestCase profile

If the project created time to check the UnitTest (from the name on the official Apple is a unit testing tool), we can see the project which is more than a default directory, one more class, as shown in fig.:

Xcode 7 intelligent test tool XCTestCase learning
select XCTest

XCTest Apple official to provide a testing tool, a built-in test framework, which can be seen from the project, a “name” of the group, we can use commond+R to travel, a test of target we can use commond+U to travel in the test target, test target directory will have a the default application name + Test class, this class not only.M.H, inherited from XCTestCase, using commond+U to run.

The default test class has the following methods:

/ / method call before calling the XCTestCase test method, can create the need for some objects used in test case method before the test - (void) setUp; / / after the test end called tearDown method, rule in all of the test case implementation after cleaning the test site, the release of resources - delete unused objects tearDown (void); / / performance test code - (void) testPerformanceExample

2.2, XCTestCase use

The initialization of XCTestCase is not a user control, developers do not need manual for XCTestCase subclass and init alloc to initialize or call a static method for operation, a function block unit test (for a class), only for this class to create a successor to the XCTestCase, after the implementation of the basic functions in the file (half of the system will default to the creation of these three functions), in fact the logic developers only need to define “test” at the beginning of the function, and then realize their functions, for a return to the numerical results, the test script can be in operation within the commond+U execution time, unit test will automatically perform these functions with test, when the blue mark appears on the head that function test, or directly to the red error.

XCTest test category:

Basic logic test processing test asynchronous loading data test data mock test

XCTest commonly used basic testing tools

XCTest some of the tools used to judge the beginning of XCT, such as:

/ / assert that the most basic test, if expression is true through, or behind the print format string XCTAssert (expression, format...) //Bool test: XCTAssertTrue (expression, format...) XCTAssertFalse (expression, format...) / XCTAssertEqual (expression1, equility test expression2, format...) XCTAssertNotEqual (expression1, expression2, format... //double) float data comparison test using XCTAssertEqualWithAccuracy (expression1, expression2, accuracy, format...) XCTAssertNotEqualWithAccuracy (expression1, expression2, accuracy, format...) //Nil test, XCTAssert[Not]Nil asserts that the given expression value is nil XCTAssertNil (expression, format...) XCTAssertNotNil (expression, format...) / failed to assert XCT Fail (format...)
XCTest asynchronous test

One of the most exciting features added to the Xcode unit test is perhaps an asynchronous test of the class XCTestExpression class. The test can now wait for a specified length of time until the test is started at some condition. And do not have to write a lot of GCD code control.

To use asynchronous testing, first create a expection using the method expectationWithDescription

Let expectation = expectationWithDescription ("...")

After that, add the method waitForExpectationsWithTimeout at the end of the method, specifying the time to wait for the timeout and the closure to be executed when the specified condition is not satisfied.

WaitForExpectationsWithTimeout (10) (error) {in} / /...

The rest is to tell the expectation condition that the condition has been met in the asynchronous callback function.

Expectation.fulfill ()
if there are multiple expectation in the test, each expectation must be fulfill, otherwise the test does not pass.

- (void) testFetchRequestWithMockedManagedObjectContext *mockContext alloc] initWithConcurrencyType:0x00] {MockNSManagedObjectContext = [[MockNSManagedObjectContext; let = MockNSManagedObjectContext (mockContext) NSFetchRequest * fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@ "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 var error: NSError? NSError *error = nil; NSArray *resu LTS = [mockContext executeFetchRequest:fetchRequest error:& error] let; results = mockContext.executeFetchRequest (fetchRequest, error: & error XCTAssertNil (error), @ "error should be nil"); XCTAssertEqual (results.count, 2, @ fetch request should only return a structure "); NSDictionary * result = results[0]; XCTAssertEqual (result[@" name "]," Zhang San "," @ @ name should be three "); NSLog (@ email:% @", "email" result[@ "); XCTAssertEqual (result[@" email "], @ @" [email protected] "," email is [email protected] ");}
XCTest Mock

Data mock

2.3, Xcode7 Code Coverage introduction

Here to talk about unit testing will inevitably be talked about a new concept, code coverage, the earliest time hear the word of the time feel very funny (don’t need the statistics), the name suggests code coverage = the actual implementation of the number of lines of code of the whole project / total number of lines of code, it is straightforward such a value, the talk, the purpose of unit testing in addition to speak each program into the smallest unit to ensure correct test, there is a code coverage problem, if sent to the online products of a considerable part of the code from the are not implemented, this problem is quite dangerous (the problem we can each guess, I believe this problem is not very strange).

Code Coverage tool use

Said the following code under Xcode coverage problems before Xcode7 code coverage statistics more trouble, after Xcode7 Apple launched a more user-friendly tool, since learning is learning the most popular, the last trouble when it go, why in pain memories (who are interested can refer to Apple DOC Xcode code coverage test tool)

Note: the traditional method of statistical coverage will be a part of the Xcode configuration, and ultimately played a “plug Zhuang package” package, this package is only used to do the statistics, if the production environment, should not be configured to turn off in a new package upload, otherwise no end of trouble for the future…

Xcode7 provides a built-in Code Coverage tool components, nonsense not to say, look at the use of the following methods:

1, the first need in product-> scheme-> Edit Scheme which will open the Code Coverage mode, selected as debug mode, as shown in figure:

Xcode 7 intelligent test tool XCTestCase learning
Edit Scheme
Xcode 7 intelligent test tool XCTestCase learning
Edit Scheme

2, open the Code Coverage mode, open a test class commond+U operation, if the test passes, the emergence of a green flag function test script on the head (opposite to which a test does not pass, it will prompt a red error), as follows:

Xcode 7 intelligent test tool XCTestCase learning
Edit Scheme

3, open the Xcode Report Navigator on the left window, find the Project Log, select the latest log options, the last is a Test Log just now, in this instance of Log, you can see the interface, as shown in figure
:

Xcode 7 intelligent test tool XCTestCase learning
Edit Scheme

Then select the Coverage in the tab, you can see the general code execution coverage, if the indicator bar is full of the code on behalf of all run over.

Xcode 7 intelligent test tool XCTestCase learning
Edit Scheme

4, you want to see the double click, choose to view UATrackDao, open can see just the test in which the code is executed, those not when the code is executed, the orange represents the execution is not executed, each row will be behind the times of a serial number on behalf of this line of code in the test execution process just in. If there is no implementation, can be adjusted according to the specific circumstances of the corresponding test script, continue to test, and ultimately ensure that each line of code can be correctly executed, as shown in figure:

Xcode 7 intelligent test tool XCTestCase learning
Edit Scheme
Xcode 7 intelligent test tool XCTestCase learning
Edit Scheme

3 Xcode7 in UITest

UnitTest profile

Any software development, UI automation testing is very important (the benefits of UI automated testing will say no more), iOS platform in the past is completed through UIAutomation UI automation testing, test case which is written by JavaScript (Instruments for the function), this process is deep and complicated, need to write your own test scripts, the learning speed is slow, high cost (about Automation test automation concept you can check the relevant information, Automation test automation application, in the major platform in software development and testing process of large indeed can save a lot of manual testing personnel, greatly improve the efficiency and cost of software testing. Recommend the use of Apple provides new tools in the latest UITest Xcode7 article).

Apple in Xcode 6 and added to the Xcode 7 UnitTest, Apple provides a new framework from the new UITest, this is mainly used to test the UI, UnitTest in test function logic code, designed to test the UI UITest.

Xcode 7 has integrated UITest, UITest allows you to find UI elements and pay households can check the UI property and the state, and UITest has been integrated in the Xcode test report, can perform together and unit test, and UnitTest as we can in time to check the UI assertions.

Create a UITest target, will also generate a “project name” UITest + group, UITest target in the construction of time to check, can also be added manually in the project, UITest + packet in the project name, we can see that the system will help us generate a default UI test class, this class the same is inherited from XCTestCase. Thus, in the iOS unit test or UI test, are based on XCTestCase.

UnitTest UI test

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

Xcode 7 intelligent test tool XCTestCase learning
Edit Scheme

To create UITest target, we test the above UI as shown in figure options:

Xcode 7 intelligent test tool XCTestCase learning
Edit Scheme
Xcode 7 intelligent test tool XCTestCase learning
Edit Scheme

Open UATrackDemoUiTest.m, create – (void) testUI, while leaving the cursor inside the function

Xcode 7 intelligent test tool XCTestCase learning
Edit Scheme

Click on the red button, start the recorder operation, the program is running, click the button on the interface, the program will push to a new page, see the mouse cursor just automatically generated part of the code, this time will repeat the operation, each will generate a new code, as shown in fig.:

Xcode 7 intelligent test tool XCTestCase learning
Edit Scheme

Click on the red button from the new button, at this time the end of the recorder operation, commond+U run test, just a series of actions will be carried out step by step:

Xcode 7 intelligent test tool XCTestCase learning
Edit Scheme

This statement: the first click on the red recorder button, and then manually will automatically generate test scripts, the second commond+U is to test UI

UnitTest tool development

XCTest provides a total of three kinds of UI test object

XCUIApplication current test application target XCUIElementQuery positioning query xctuielement in the current UI in a class XCUIElement UI test in any of the item items are abstracted into a XCUIElement type

When we get the record generated code, according to the three objects provided by the UITest, I can do this to modify the test code, debugging
UITest also applies to the following assertions:

XCTAssert (expression, format...) //Bool test: XCTAssertTrue (expression, format...) XCTAssertFalse (expression, format...) / XCTAssertEqual (expression1, equility test expression2, format...) XCTAssertNotEqual (expression1, expression2, format...) //double float data comparison test using XCTAssertEqualWithAccuracy (expression1, expression2, accuracy, XCTAssertNotEqualWithAccuracy (format...) expression1, expression2, accuracy, format...) //Nil test, XCTAssert[Not]Nil asserts that the given expression value is nil XCTAssertNil (expression, format...) XCTAssertNotNil (expression, format...) / / XCTFail failed assertions (format...).....

Xcode 7 UnitTest on the issue here, I hope the students are interested in common communication…

4 Summary

1 summarize existing problems and share experiences

Xcode6’s built-in tools are finally good enough. That is, even a large APP is not necessary for the unit test code coverage and exclusion of Xcode built-in test tools. No matter what kind of test, XCTest’s assertions, expectation, and performance tests are sufficient. But no matter how good the tool, you need to make good use of it.

If you are testing iOS or OS X APP, start adding some assertions to the class that you automatically add and press Command+U. You will find it easy to feel these tools to make your test.

WWDC2015 What’s New in Xcode
WWDC2015 UI Testing in Xcode
WWDC2015 Testing in Xcode Mattt Thompson Blog 6

Xcode own use unit testing
Parse source code method-swizzling