最近在做iOS的变异测试,有一部分是需要根据覆盖率精准推荐单测用例,其中设计到ios的单测,今天我们就聊聊 iOS的单测
1、查看xcodebuild命令
man xcodebuild
即可查看xcodebuild所支持的选项
2、xcodebuild完整的单元测试命令
xcodebuild test -workspace 'xxx.xcworkspace' -scheme xxx -destination 'platform=iOS simulator,id=82D4328F-F862-4BC5-A3B2-41F044E444AB' -enableCodeCoverage YES -default-test-execution-time-allowance 0.5 -test-timeouts-enabled YES -maximum-test-execution-time-allowance 0.5 -resultBundlePath 'xxx.xcresult' -only-testing xxx/yyy/zzz
-workspace
工程名字-destination
单元测试的执行机-only-testing
运行某一个单测用例-skip-testing
跳过某一个单测用例
-only-testing
和 -skip-testing
输入格式是TestTarget[/TestClass[/TestMethod]]
-destination
可以通过命令 instruments -s devices
获取,选择符合工程的设备(因为工程可能会设置最低操作系统要求)
3、xcodebuild编译和运行
只编译不运行
xcodebuild build-for-testing xxx
只运行不编译
xcodebuild test-without-building
编译+运行
xcodebuild test
4、查看覆盖率
4.1 以json格式查看报告
xcrun xccov view --report --json Demo.xcresult
4.2 以默认格式查看报告
xcrun xccov view --report Demo.xcresult
4.3 查看被覆盖的文件
xcrun xccov view --archive --file-list Demo.xcresult
4.4 查看文件覆盖的行号
xcrun xccov view --archive --file 'xxx' Demo.xcresult
5、并行执行单元测试
并行测试可以同时在多个目标上进行测试。我们可以按下面的方式来在不同测试目标上并行测试:
xcodebuild test
-destination 'platform=iOS,name=iPhone X'
-destination 'platform=iOS,name=iPad'
并行测试最好先把模拟器预先启动起来,启动模拟器命令如下:
xcrun instruments -w 模拟器
6、Xcodebuild执行单元测试超时
xcode11.4 增加了执行单元测试的超时参数,在启用-test-timeouts-enabled 选项后为单个测试配置默认执行时间,请传递 -default-test-execution-time-allowance 选项。要对测试的运行时间强加绝对上限(如果它通过executeTimeAllowance API请求更多时间),请传递 -maximum-test-execution-time-allowance 选项。但是在实际的实践中发现 -maximum-test-execution-time-allowance参数不生效,超时时间永远是1分钟
参考文章
1、https://developer.apple.com/library/archive/technotes/tn2339/_index.html#//apple_ref/doc/uid/DTS40014588-CH1-PRODUCT
2、https://www.thinbug.com/q/20237064
3、https://www.hualong.me/2018/03/14/Xcodebuild/
4、https://www.jianshu.com/p/f88d5efbc98f
5、https://medium.com/xcblog/xccov-xcode-code-coverage-report-for-humans-466a4865aa18
6、https://xiaozhuanlan.com/topic/3790216845
7、https://www.jianshu.com/p/4413d6879457
8、https://ohmyrss.com/post/1585243964646