![](/img/trans.png)
[英]How can I present a ViewController using applicationdidBecomeActive func with some exceptions?
[英]How can I run xctest for return ViewController func
如何为以下代码编写 XCTestCase
class HelpViewUseCase: HelpUseCaseProtocol, SubscriptionsHelpProtocol, ProfileHelpProtocol {
func getHelpViewController() -> UIViewController {
HelpViewController()
}
}
另一个我无法测试的课程
class UnifiedDirectAppointmentViewModel: UnifiedHistoryRowViewModel {
var rowType: UnifiedHistoryTableRowType {
.directBooking
}
let appointmentResponse: DirectBookingInfoModel
init?(forRowModel rowModel: UnifiedHistoryRowModel) {
guard let data = rowModel.data.data as? DirectBookingInfoModel else {
Log.error("Failed init for appointment \(rowModel)")
return nil
}
appointmentResponse = data
}
}
extension UnifiedDirectAppointmentViewModel {
var reuseIdentifier: String {
DirectAppointmentTableViewCell.identifier
}
var bundle: Bundle? {
Bundle(for: DirectAppointmentTableViewCell.self)
}
}
我是单元测试的新手,想知道如何测试 aove 类。 提前感谢您的建议和帮助
单元测试(或“微测试”)应该:
这是一个通常称为 3 A 的序列,即A rrange、 A ct、 A ssert。 我喜欢用空行分隔它们,以明确每行测试代码所扮演的角色。
对于您的第一个示例,您有getHelpViewController()
它返回一个UIViewController
,特别是一个HelpViewController
。 所以我们可以测试如下。 (我通常不使用注释,但在这里这样做是为了为您确定每一行的目的。)
// The class creates a test suite, a collection of tests.
// Subclass XCTestCase.
// Name it after the type you want to test, and add "Tests".
// final is not required, but can give a minor speed improvement.
final class HelpViewUseCaseTests: XCTestCase {
// In XCTest, a test method must start with the letters "test".
// Name it for the behavior you want to test.
// In this case, the name of the method is good enough.
// The underscore is not required. I just like the separation in the name.
// I declare all my test methods as throwing because it
// makes it easier to use throwing test helpers like XCTUnwrap.
func test_getHelpViewController() throws {
// Arrange
let useCase = HelpViewUseCase()
// Act
let result = useCase.getHelpViewController()
// Assert
XCTAssertTrue(
result is HelpViewController,
"Expected a HelpViewController, but was a \(type(of: result))"
)
}
}
我向XCTAssertTrue
添加了一条消息,因为如果它失败了,我想知道的不仅仅是“这不是真的”。 我想知道为什么。 所以我有消息说明期望和实际类型。 尝试通过返回错误类型的视图控制器来破坏生产代码以查看消息的外观。 (在编写测试时,重要的是让它以某种方式失败以检查它是否正常工作,以及失败是否提供了足够的信息。)
您的第二个示例实际上是一个单独的问题,不应与另一个问题混为一谈。 欢迎直接给我留言。
我写了一本书,可以帮助你开始在 Swift 中进行单元测试。 有关详细信息,请参阅我的个人资料。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.