单元测试 + UI测试

一. 单元测试

简介:

单元测试, 又称模块测试, 是针对程序模块的最小单位来进行测试. 对于过程化变成来说, 一个单元就是单个函数 过程等; 对于面向对象变成来说, 一个单元就是一个方法.

有了单元测试, 我们不需要每次都com+R 启动我们的程序,对于大的项目来说, 启动一次项目都会花费很长时间, 这时使用单元测试, 就方便了很多;

使用:

1.  添加测试文件

a.在创建项目的时候, 可以直接勾选include Unit Test

b.项目已存在, 可添加: File -> New -> Target -> Unit Test

文件中默认包含的四个方法:

 - (void)setUp
//初始化的代码,在测试方法调用之前调用
- (void)tearDown
// 释放测试用例的资源代码,这个方法会每个测试用例执行后调用
- (void)testExample 
// 测试用例的例子,注意自己写的测试用例方法 一定要test开头
- (void)testPerformanceExample {
// 测试性能例子
[self measureBlock:^{
    // Put the code you want to measure the time of here.
// 需要测试性能的代码
}];
}

2.测试 某个类中的方法

例如:

- (void)setUp {

    [super setUp];

 

    self.vc = [[ViewController alloc] init];

}

 

- (void)tearDown {

 

    self.vc = nil;

    

    [super tearDown];

}

 

- (void)testMyFuc {

    

    // 调用需要测试的方法,

    int result = [self.vc getNum];

    // 如果不相等则会提示@“测试不通过

    XCTAssertEqual(result, 200,@"测试不通过");

}

 

二. UI 测试

需要写一些代码, 来模拟 人为的操作, 从而根据结果,来判断正确与否

- (void)testLogin{

    [XCUIDevice sharedDevice].orientation = UIDeviceOrientationFaceUp;

    [XCUIDevice sharedDevice].orientation = UIDeviceOrientationFaceUp;

    

//XCUIApplication 这是应用的代理,他能够把你的应用启动起来,并且每次都在一个新进程中。

    XCUIApplication *app = [[XCUIApplication alloc] init];

//XCUIElement 这是 UI 元素的代理。元素都有类型和唯一标识。可以结合使用来找到元素在哪里,如当前界面上的一个输入框

    XCUIElement *usernameTextField = app.textFields[@"username:"];

    [usernameTextField tap];

    [usernameTextField typeText:@"xiaofei"];

    

    XCUIElement *passwordTextField = app.textFields[@"password:"];

    [passwordTextField tap];

    [passwordTextField tap];

    [passwordTextField typeText:@"12345"];

    [[[[[[[app childrenMatchingType:XCUIElementTypeWindow] elementBoundByIndex:0] childrenMatchingType:XCUIElementTypeOther].element childrenMatchingType:XCUIElementTypeOther].element childrenMatchingType:XCUIElementTypeOther].element childrenMatchingType:XCUIElementTypeOther].element tap];

    [app.buttons[@"login"] tap];

    

//登录成功后的控制器的title为loginSuccess,只需判断控制器的title时候一样便可判断登录是否成功

//    XCTAssertEqualObjects(app.navigationBars.element.identifier, @"loginSuccess");

    

    XCTAssertEqual(app.navigationBars.element.identifier, @"loginSuccess",@"测试不通过");

 

}

 

 

 

参考链接:

http://www.jianshu.com/p/07cfc17916e8

原文地址:https://www.cnblogs.com/daxueshan/p/7364270.html