iOS-UI测试

上一节讲了单元测试,本节简单的讲下UI测试即 UITest。在项目开的发的时候页面上可能会有大量的控件导致滑动卡顿,导致用体验下降,这里用UI测试来j尽量避免这种情况。

1.创建项目的时候勾选 Include UI Tests
这里写图片描述
这里写图片描述

2.进入UnitTestUITestsUI测试类里面看到有几个方法

- (void)setUp {
    [super setUp];

    // 每次都要置空

    // Put setup code here. This method is called before the invocation of each test method in the class.

    // In UI tests it is usually best to stop immediately when a failure occurs.
    self.continueAfterFailure = NO;
    // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.

    // 因为下面一句,所以每次测试完就会退出一下
    [[[XCUIApplication alloc] init] launch];

    // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}

- (void)tearDown {
    // Put teardown code here. This method is called after the invocation of each test method in the class.
    [super tearDown];
}

注意:在UI测试的时候,每次测试完你会发现App就会退出,这是因- (void)setUp方法里面有[[[XCUIApplication alloc] init] launch];表示每次都会重新启动这个App。

3.写个小例子

  - (void)testPlus
{
    XCUIApplication *app = [[XCUIApplication alloc] init];
    [app.buttons[@"4"] tap];
    [app.buttons[@"+"] tap];
    [app.buttons[@"5"] tap];
    [app.buttons[@"="] tap];
    int n = 4 + 5;
    XCTAssertEqual(n, 9);  
}

点击这个运行按钮:
这里写图片描述

你会发现页面上的按钮在自动点击。

4.录制 UI Test

UI Test的录制功能是非常棒的,使用录制按钮开始录制UI Test,此时模拟器会自动启动,可以点击屏幕进行操作。

这里写图片描述

这里写图片描述

这个时候你就可以操作模拟器上面的控件,然后观察- (void)testExample方法。

- (void)testExample {
    // Use recording to get started writing UI tests.
    // Use XCTAssert and related functions to verify your tests produce the correct results.

    XCUIApplication *app = [[XCUIApplication alloc] init];
    [app.buttons[@"1"] tap];

    XCUIElement *button = app.buttons[@"2"];
    [button tap];
    [app.buttons[@"3"] tap];

    XCUIElement *button2 = app.buttons[@"+"];
    [button2 tap];

    XCUIElement *button3 = app.buttons[@"6"];
    [button3 tap];

    XCUIElement *button4 = app.buttons[@"5"];
    [button4 tap];
    [app.buttons[@"7"] tap];

    XCUIElement *button5 = app.buttons[@"="];
    [button5 tap];
    [button4 tap];
    [button3 tap];
    [button tap];
    [button2 tap];
    [button3 tap];
    [button5 tap];

}

操作完之后再点击那个录制按钮就结束录制,然后测试这个方法,模拟器面就回按照你之前操作过的步骤再次演示一遍。这个录制功能最大的好处就是,程序员不需要写那么多测试代码,系统帮我们自动生成了测试代码。

Demo下载地址 https://github.com/MichaelSSY/UITest-UnitTest

猜你喜欢

转载自blog.csdn.net/ssy_1992/article/details/79348809