Swift单元测试XCTest

创建项目的时候可以勾选UnitTest选项,系统会自动生成Test Target,没有勾选的也可以自行创建Test Target

1、对于OC混编的项目,Test工程会报找不到头文件错误。需要在Test Target的build setting中配置bridging-header。
2、对于CocoaPods引入的第三方库,也会报找不到,可以在Podfile中增加KuaiTests部分代码,如下
platform :ios, '9.0'
use_frameworks!

def pods
#Swift3
pod 'SlideMenuControllerSwift'
pod 'IQKeyboardManagerSwift'
pod 'Alamofire' , '~> 4.0'
pod 'ObjectMapper'
pod 'Kingfisher'
    pod 'GzipSwift'
#Objective-C
    pod 'MBProgressHUD'
    pod 'MJRefresh'
    pod 'UMengAnalytics-NO-IDFA'
    pod 'Bugly'
    pod 'JPush'
    pod 'FCUUID'
end

target 'Kuai' do
    pods
end

target 'KuaiTests' do
    pods
end

post_install do |installer|
  installer.pods_project.targets.each do |target|
    target.build_configurations.each do |config|
      config.build_settings[ 'SWIFT_VERSION' ] = '3.0' # or '3.0'
    end
  end
end

3、App中的private、fileprivate方法和属性,在Test中是不能访问的。如果非要访问,只能在代码里改成internal或者public
4、mock运用的动态特性,swift中有些东西是不支持的,比如枚举和结构体。可以在Test文件中写Extension,override原有方法的实现,就行了。
5、本地引入的第三方库,还需要在Test Target的build setting中配置Search path相关的引用。
6、异步调用,可以用dispatch_group控制,全部完成后再走下个测试。还可以用 XCTestExpectation,如下
    func testBankCardListAPI() {
        let expectation = self . expectation (description: "Handler called" )
        NetworkAPIs . sharedInstance . getBankList (successHandler: { (response) in
            expectation. fulfill ()
            XCTAssertNotNil (response, " 接口返回数据为空 " )
            print (response)
        }) { (errorCode, errorMsg) in
            expectation. fulfill ()
            XCTAssertThrowsError ( " 请求失败 " )
        }
        self . wait (for: [expectation], timeout: 60.0 )
    }

猜你喜欢

转载自blog.csdn.net/pilgrim1385/article/details/77947175