【问题标题】:Generic XCTAssertEqual with AnyObject arguments?带有 AnyObject 参数的通用 XCTAssertEqual?
【发布时间】:2016-03-21 22:54:16
【问题描述】:

在测试NSLayoutConstraint 项目时,此行无法编译:

XCTAssertEqual(firstItem, view1)

错误:无法使用“(AnyObject, AnyObject)”类型的参数列表调用“XCTAssertEqual”

为了让它在没有错误或警告的情况下编译,我必须这样做:

XCTAssertEqual(firstItem as? UIView, view1 as? UIView)

但是,我不知道firstItemview1UIView 还是UILayoutSupport,等等。

那么,有没有通用的方法来测试这个?

对于上下文,我在我编写的测试辅助方法中执行此操作:

extension NSLayoutConstraint {
    func assert(item view1: AnyObject, toItem view2: AnyObject? = nil, attribute attr1: NSLayoutAttribute, relatedBy relation: NSLayoutRelation = .Equal, attribute attr2: NSLayoutAttribute? = nil, multiplier: CGFloat = 1, constant c: CGFloat = 0) {
        let attribute2: NSLayoutAttribute = view2 == nil ? .NotAnAttribute : (attr2 ?? attr1)
        XCTAssertEqual(firstItem as? UIView, view1 as? UIView)
        XCTAssertEqual(firstAttribute, attr1)
        XCTAssertEqual(self.relation, relation)
        XCTAssertEqual(secondItem as? UIView, view2 as? UIView)
        XCTAssertEqual(secondAttribute, attribute2)
        XCTAssertEqual(self.multiplier, multiplier)
        XCTAssertEqual(constant, c)
    }
}

【问题讨论】:

  • 如果您只是创建了一个函数,该函数在 AnyObject 比较中返回 true 并改用 XCTAssertTrue 怎么办?
  • 谢谢。我搜索了 swift compare anyobject 并找到了答案。
  • SwiftHamcrest 提供了另一种选择:assertThat(firstItem, sameInstance(view1))

标签: swift generics nslayoutconstraint xctest anyobject


【解决方案1】:
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-07
  • 1970-01-01
相关资源
最近更新 更多