[iOS translator] "IOS7 by Tutorials" in Xcode 5 using unit test (UP)

Source: Internet
Author: User

Brief introduction:

Unit testing is an important aspect of software development. After all, unit testing can help you find bugs and crash reasons, and program crashes are the primary reason Apple rejects apps when it's censored.

Unit testing is not a panacea, but Apple as part of the development toolkit not only makes your app more stable, but also provides a consistent and fun user experience, which is the source of a five-star rating for your users. The IOS7 provides an upgraded unit testing framework. Allowing you to perform unit tests in Xcode is easier. When you're finished, you'll learn how to add a test to an existing app-and possibly develop a passion for writing tests!


This article translated from "IOS7 by Tutorials" a book of the 11th chapter "Unit Testing in Xcode 5", want to experience the essence of the original friend please to Raywenderlich Shop support genuine.

—————— (Blog Park, Sina Weibo) Galbrain the Great



First, unit test basis

Second, start the project

Third, where to go next?

Iv. challenges

Appendix: Xctest Assertion References

First, unit test basis

In the past. Xcode introduces an open-source unit testing framework called Ocunit . And in Xcode 5. Apple has unveiled its own unit testing framework, called Xctest.

Suppose you are already familiar with Ocunit. Don't worry,xctest is a similar API built on top of Ocunit and 10 copies.

Transitioning from Ocunit to Xctest is easy. To do but replace Stfail with Xctfail, Stassert to Xctassert, and so forth. Assuming you are familiar with these basics, you can jump directly to the next section.

1. High-level overview

There are four levels of unit test. From top to bottom, each of them is:

  • Testing Suite (test suite)
    • This is all the set of tests in the project. In Xcode, the test kit is set to a separate build target.
  • Test Case Class (classes)
    • As you might expect, in an object-oriented system. Tests are integrated into the class.

      In your app, each test class usually corresponds to a separate class. For example, the Developertests class should test the developer class accordingly.

  • Sample method (test case methods)
    • Each test class includes a variety of methods. Various functions used to test the class. Just as a method or function should be both streamlined and useful, each test example should test a specific result-and test it completely.

  • Assertion (assertions)
    • The assertion examines the detailed criteria for the corresponding expected result. If the condition does not match the expected result, Xcode will report an error stating that the assertion failed. For example, be able to assert your developer class response "Writekillerapp:message"; Assertion failed with Xcode error.

The theory is very good. But sometimes it's easier to illustrate things. Create a new project with the Empty application template, named Emptyapp. The Xcode template will voluntarily include a test target called emptyapptests , added to the Emptyapp app Target, for example:

Note the sample class includes a. m file without an associated header file. Open the emptyapptests.m to see the source of the first Test example.

Test methods must start with the word test so that test runner can find them.

In your Demo sample project. The test class includes a test method called testexample.

The setUp and TearDown methods are like guards around the test case.

Put all the object's program code or repetitive code into Setup . Keep the test sample method fresh and efficient.

Similarly, methods for closing file handles or canceling cleanup activities such as suspending network requests should be placed in the teardown.

Test Runner calls the setup, Testexample, and teardown methods in turn . Suppose you affirm the second test method Testsecondexample. Test Runner will call setup, Testsecondexample, and finally the Teardown method. Suppose you have multiple test methods. Setup and teardown will be called multiple times in a test session-every time a test sample method is called!

The moral of this story is not to put anything that is too slow or too frequently handled into the Setup or Teardown method . -This will give you a long wait to execute the test kit !

2. Create your first Test

The Testexample method only has a statement called Xctfail, as it implies in its name: it will always fail. This statement is not very practical, you can write a better than it! Remove the Testexample method and add the following methods, for example:

-(void) test_addition_twoplustwo_isfour {xctassert (224@ " 2 + 2 should is 4 but%d is returned instead " 2+2);}

A frequently used naming standard for test cases is: Unitofwork_stateundertest_expectedbehavior (Work Unit _ test state _ expected behavior).

In this example, the measured unit of work is addition, the test state is 2 + 2, the expected behavior is the result of 4.

All xctest assertions have a prefix of XCT. Xctassert is a simple assertion that can be used for unit testing, and the first parameter is an expression that is pre-evaluated as ture, and when an assertion fails, a message is displayed after the NSLog-style parameter.

Make sure that the current target of the project is the iphone emulator, and the simulator will start and execute the test kit by using product---Test (COMMAND-U) on the top folder of the form. Assuming the notification is active, you will see the following confirmation message:

To verify that the first unit tested successfully, switch to test Navigator. The arrows indicate it:

Ha ha!

Your unit test is shown next to the emerald green hook.

You can also see the code next to the Diamond icon in the blank of the border, as seen in the following:

These icons show the status of the associated test code:

A green tick next to the @implementation indicates that the test passed. The green tick beside the Test_addition_twoplustwo_isfour indicates that this method is tested.

At the same time, these icons are also button:

Clicking on the icon next to @implementation will perform all tests of this class, and clicking on the icon next to the test method will perform the test, and try it!

Now that you have a preliminary understanding of the concept and operation of the test, it's time to start the Demo sample project in this chapter--and start with a test.

Second, start the project

In the remainder of this chapter you will use a black-and-white game project called Reversi, rules: Two players representing White and black, alternately lazi on the 8x8 chessboard.

Eat it by enclosing the opponent's pieces. At the end of the game, the most chess player wins.

How to create this game, see: http: // www.raywenderlich.com/29228/how-to-develop-an-ipad-board-game-app-part-12

Download the Demo sample project provided at the end of this article and execute it and click on the Vs computerbutton at the bottom of the screen to play against the computer and experience the interface and gameplay of the game.

Did you win? Or was the AI opponent burst out? Anyway. Your job is not playing games all day-it's time to add some practical tests to the project.

1. Join the test support

The first one that needs to be tested is the GameBoard class.

This class contains the basic logic of the 8x8 chessboard, where each of the 64 cells has a state--empty, black, or white--and the GameBoard instance allows you to get and set the state of each block.  

Open GameBoard.h look at the method inside, it's a good idea to figure out the function and implementation of each method before you start writing tests for existing code.

In GameBoard.h. You will see the following two methods:

Gets the state of the cell at the given location//raises an nsrangeexception if the column or row is out of bounds-( Boardcellstate) Cellstateatcolumn: (nsinteger) column Androw: (nsinteger) row;//sets the state of the cell at the given Locat ion//raises an nsrangeexception if the column or row is out of bounds-(void) Setcellstate: (boardcellstate) State Forcolu MN: (nsinteger) column Androw: (nsinteger) row;

Cellstateatcolumn:androw: And SetCellState:forColumn:andRow: Developed in Getter/setter mode that you are familiar with. Your first test is to run actions such as the following:

    • Initializing a GameBoard instance
    • Setting the cell state
    • Get cell status
    • Gets the cell state from the specified cell

The first step is to create a GameBoard test class. Right-click the reversigametests group. Select Ios\cocoa touch\objective-c test Case Class to create a test class named Gameboardtests. Inherit from Xctestcase.

Make sure your new test example is added to reversigametests target. For example (this step is important, assuming that you did not add to the correct target, your test will not be executed):

Open gameboardtests.m and delete the Testexample method, you don't need it.

Then import the header file at the top of the gameboardtests.m (which allows your test class to access the GameBoard Class): GameBoard.h

#import "GameBoard.h"

You need to provide a gameboard instance for all of your tests. Creating an instance variable is much more refreshing than declaring it in every test.

In gameboardtests.m update @interface For example the following:

GameBoard *_board;}

Now that you have the _board instance variable, you can start testing.

The Setup method is a good place to initialize the _board for the first time, and change setup such as the following:

-(void) setup{[Super setUp]; _board = [[GameBoard alloc] init]; }

Now all of this class's test-case methods can access the initialized _board instance variables.

2. First Test

This is the first test you need to add the full steps, add the following method to gameboardtests.m:

-(void) test_setandgetcellstate_setvalidcell_cellstatechanged {[_board setcellstate:boardcellstatewhitepiece  Forcolumn:4 Androw:5];     Boardcellstate retrievedstate = [_board cellstateatcolumn:4 androw:5]; Xctassertequal (Boardcellstatewhitepiece, Retrievedstate, @ "The cell should be white!");}

The above code sets a white in the (4,5) cell, and immediately retrieves the state of the same cell. Xctassertequal assertions check that they are equal, assuming they are not equal. You will see an exception message, and then you will learn that there is something that needs to be checked.

The method name of the above code follows the format I mentioned earlier, and with this method name, you can easily see that it tests the setter and getter method by setting the correct cell position, and expects the cell state to change.

Assuming your test work is planned, make sure that the iphone and ipad Simulator are tested and then perform a test (command-u).

Switch to test Navigator and you will see a green tick indicating that the test passed, for example by:

This seems to be just a simple test. However, it provides great value in debugging errors.

Internally, the GameBoard class uses a simple two-dimensional array to track the 8x8 checkerboard. But assuming you've changed the array of vectors or matrices before, this test will be used as a regression test to ensure that the base of the interface is still working.

As an added bonus, writing a test for an existing class can greatly help you understand how the code works. The method of analyzing the class can help you identify its function and facilitate your test writing.

3. Test anomalies

Testing the code in accordance with the designed functionality helps ensure its correctness, but it also makes your app "early or high-profile failure"-those with abnormal game state or invalid conditions being caught very quickly by the debugger.

GameBoard.h Cellstateatcolumn:androw: And SetCellState:forColumn:andRow: The gaze of the method indicates that if the row or column exceeds the checkerboard border, they will eject the error.

It looks like you've found a lot of other test conditions.

Add the following two methods:

-(void) Test_setcellstate_withinvalidcoords_exceptionthrown {xctassertthrowsspecificnamed ([_board setCellState: Boardcellstateblackpieceforcolumn:10androw:7], nsexception,nsrangeexception,@ "out-of-bounds board set should raise An exception ");} -(void) Test_getcellstate_withinvalidcoords_exceptionthrown {xctassertthrowsspecificnamed ([_board Cellstateatcolumn:7 androw:-10],nsexception,nsrangeexception,@ "out-of-bounds board access should raise an exception") ;}

in the code above. Test_setcellstate_withinvalidcoords_exceptionthrown: Attempting to set the out-of-range cell (10,7) at the same time Test_setcellstate_ Withinvalidcoords_exceptionthrown: An attempt was made to get an out-of-range cell (7,-10). Again, the method name has been pointed at the wrong coordinates of the positive test. The unusual report was expected.

Xctassertthrowsspecificnamed uses the following four points as the number of parameters:

    • An expression that should be reported as abnormal
    • Excluded classes
    • Excluded names
    • Message displayed when a test fails

Click Command-u to perform the test. You should see the following results

What is it? You want to pass the test with great code, but two errors are flagged on issue navigator. The test failure message is also displayed on the code. For example, with:

The full test failure message is:

[Gameboardtests Test_getcellstate_withinvalidcoords_exceptionthrown] Failed: (([_board Cellstateatcolumn:7 andRow:- ]) throws <nsexception, "Nsrangeexception" >) failed:throwing <nsexception, "Nsgenericexception", "row or Column out of bounds ' >-out-of-bounds board Access should raise an exception

Suppose you break up the message above. You will see that the behavior you want is (throws <nsexception, "Nsrangeexception" >), while what actually happens is (throwing <nsexception, "nsgenericexception" >).

In this example, you are looking for nsrangeexception. But the received is nsgenericexception.

Looks like you've done some research!

Demo Sample Project address: http: // Pan.baidu.com/s/1o6x6zxg

[iOS Translator] "IOS7 by Tutorials" in Xcode 5 using unit test (UP)

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.