概览
这个库允许您编写单元测试来测试视图在多种配置下的布局。它使用不同的数据组合和不同的视图大小来测试视图。此库在Objective-C和Swift中都能使用。
要了解如何使用这个库,有一个由Kyle Sherman编写的LinkedIn Learning课程可供您免费访问。您可以通过以下链接访问:[这里](https://www.linkedin.com/learning/learning-layouttest-for-ios-development)。该课程将教授您如何通过视频教程使用LayoutTest及其所有功能。
动机
当创建视图时,应用程序通常有依赖于用于设置视图的数据的条件的逻辑。LayoutTest提供了一种轻松定义数据规范(字典)的方法,然后用它来生成许多不同的数据组合。然后,该库使用这些数据多次布局您的视图。例如,这是我们在示例应用中运行的测试的一部分
在一个测试中,您的视图将以不同的数据多次布局。然后您可以对这些视图运行测试断言,以验证布局和视图内容是否正确。此外,该库会自动运行一些测试,例如检查自动布局错误、缺失可访问性和重叠视图。最后,该库使您能够以不同的尺寸测试每个视图,以验证视图是否可以在不同设备上正常工作。
文档
要开始,您应该查看文档
https://linkedin.github.io/LayoutTest-iOS
安装
将其添加到您的单元测试目标中
pod 'LayoutTest'
或者
pod 'LayoutTest/Swift'
示例
一个简单的测试看起来可能像这样。查看文档以获取更多详细信息和其他示例。
Objective-C
@interface SampleTableViewCellLayoutTests : LYTLayoutTestCase
@end
@implementation SampleTableViewCellLayoutTests
- (void)testSampleTableViewCellLayout {
[self runLayoutTestsWithViewProvider:[SampleTableViewCell class]
validation:^(UIView * view, NSDictionary * data, id context) {
// Add your custom tests here.
}];
}
@end
@implementation SampleTableViewCell (LayoutTesting)
+ (NSDictionary *)dataSpecForTest {
return @{
@"text": [[LYTStringValues alloc] init],
@"showButton": [[LYTBoolValues alloc] init]
}
}
+ (UIView *)viewForData:(NSDictionary *)data
reuseView:(nullable UIView *)reuseView
size:(nullable LYTViewSize *)size
context:(id _Nullable * _Nullable)context {
SampleTableViewCell *view = (SampleTableViewCell *)reuseView ?: [SampleTableViewCell viewFromNib];
[view setupWithJSON:data];
return view;
}
@end
Swift
class SampleTableViewCellLayoutTests {
func testSampleTableViewCell() {
runLayoutTests() { (view: SampleTableViewCell, data: [NSObject: AnyObject], context: Any?) in
// Add your custom tests here.
}
}
}
extension SampleTableViewCell: LYTViewProvider {
class func dataSpecForTest() -> [NSObject: AnyObject] {
return [
"text": LYTStringValues(),
"showButton": LYTBoolValues()
]
}
class func viewForData(data: [NSObject: AnyObject],
reuseView: UIView?,
size: LYTViewSize?,
context: AutoreleasingUnsafeMutablePointer<AnyObject?>) -> UIView {
let cell = reuseView as? SampleTableViewCell ?? SampleTableViewCell.loadFromNib()
cell.setupWithDictionary(data)
return cell
}
}