LayoutTestBase 6.1.0

LayoutTestBase 6.1.0

测试已测试
Lang语言 Obj-CObjective C
许可证 Apache-2.0
发布最新发布2024年5月

Peter LiveseyPeter LiveseykhuDoug YoungChris LeonaviciusKyle ShermanMani RamezanGuo LiMac Gallagher维护。



  • 发起人
  • LinkedIn

概述

该库允许您编写单元测试来测试视图在不同配置下的布局。它使用不同的数据组合和不同的视图大小来测试视图。库在Objective-C和Swift中都有效。

要了解如何使用此库,有一个由Kyle Sherman撰写的LinkedIn Learning课程,您可以完全免费访问。您可以在这里找到此课程。它将通过视频教程教授您如何使用LayoutTest及其所有功能。

动机

当创建视图时,应用程序往往包含依赖于用于设置视图的数据的复杂逻辑。LayoutTest提供了一个简单的方式来定义一个数据规范(一个字典),然后用于生成许多不同的数据组合。然后库使用这些数据多次布局视图。例如,这是在我们的示例应用程序中运行的一小部分测试

在一个测试中,您的视图将多次使用不同的数据来布局。然后您可以对这些视图运行测试断言以验证布局和视图内容是否正确。此外,库会自动运行一些测试,例如检查Autolayout错误、缺少可访问性和视图重叠。最后,该库使您能够以不同的尺寸测试每个视图,以确保视图适用于不同的设备。

文档

要开始使用,您应该查看文档

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
  }
}