XCTAssertEqual给了我错误 - UIViewController.Type 无法符合'Equatable'



我有一个类似于以下的枚举-

enum Vehicle: String, CaseIterable {
case car = "/car/"
case boat = "/plane"
case bicycle = "/bicycle/"
case train = "/train"

var targetControllerType: UIViewController.Type? {
switch self {
case .car:
return FourWheelerViewController.self
case .boat:
return NoWheelerViewController.self
case .bicycle:
return TwoWheelerViewController.self
case .train:
return MultiWheelerViewController.self
}
}
}

当我进行相等性检查时,它是有效的-

if Vehicle.train.targetControllerType == MultiWheelerViewController.self {
print("It's true")
}

但是当我尝试为它写测试用例时,比如-

func testTrainTargetViewControllerType() {
XCTAssertEqual(Vehicle.train.targetControllerType, MultiWheelerViewController.self)
}

我得到编译时错误-

Type UIVewController.Type" canot conform to 'Equatable'.

有人能告诉我这里发生了什么以及为什么吗。

正如错误所说,Type不符合Equatable。但您仍然可以使用==:测试相等性

func testTrainTargetViewControllerType() {
XCTAssertTrue(Vehicle.train.targetControllerType == MultiWheelerViewController.self)
}

这就过去了。但如果测试失败了,它没有说明原因。我们通常会从XCTAssertEqual得到一条有用的消息,因为它可以说左侧不等于右侧,所以我们可以看到这两个值。

但是每个XCTest断言都有一个可选消息,我们可以在其中添加信息。因此,添加一条消息,说明您的预期以及实际结果:

func testTrainTargetViewControllerType() {
XCTAssertTrue(
Vehicle.train.targetControllerType == MultiWheelerViewController.self,
"Expected MultiWheelerViewController, but was (String(describing: Vehicle.train.targetControllerType))"
)
}

强制测试失败,看它有多有用。如果我故意破坏代码,我会看到:

XCTAssertTrue failed - Expected MultiWheelerViewController, but was Optional(MyProject.TwoWheelerViewController)

这样,如果出现任何错误,您就可以获得所需的信息,以了解它为什么无法通过断言。

最新更新