文章40 | 阅读 19086 | 点赞0
class UserServiceTests: XCTestCase {
func testLoggingIn() {
// 为了登陆终端
// 构建一个永远返回成功的模拟对象
let networkManager = NetworkManagerMock()
networkManager.mockResponse(forEndpoint: .login, with: [
"name": "John",
"age": 30
])
// 构建 service 对象以及登录
let service = UserService(networkManager: networkManager)
service.login(withUsername: "john", password: "password")
// 现在我们想要基于已登陆的用户进行断言,
// 这是可选类型,所以我们对它进行强制解析
let user = service.loggedInUser!
XCTAssertEqual(user.name, "John")
XCTAssertEqual(user.age, 30)
}
}
Fatal error: Unexpectedly found nil while unwrapping an Optional value
guard let user = service.loggedInUser else {
XCTFail("Expected a user to be logged in at this point")
return
}
let user = service.loggedInUser
XCTAssertNotNil(user, "Expected a user to be logged in at this point")
XCTAssertEqual(user?.name, "John")
XCTAssertEqual(user?.age, 30)
XCTAssertNotNil failed - Expected a user to be logged in at this point
XCTAssertEqual failed: ("nil") is not equal to ("Optional("John")")
XCTAssertEqual failed: ("nil") is not equal to ("Optional(30)")
class EndpointURLFactory {
func makeURL(for endpoint: Endpoint) -> URL? {
...
}
}
class EndpointURLFactory {
func makeURL(for endpoint: Endpoint) throws -> URL {
...
}
}
let loginEndpoint = try? urlFactory.makeURL(for: .login)
class EndpointURLFactoryTests: XCTestCase {
func testSearchURLContainsQuery() throws {
let factory = EndpointURLFactory()
let query = "Swift"
// 因为我们的测试函数是 throwing,这里我们可以简单地采用 'try'
let url = try factory.makeURL(for: .search(query))
XCTAssertTrue(url.absoluteString.contains(query))
}
}
let user = try require(service.loggedInUser)
XCTAssertEqual(user.name, "John")
XCTAssertEqual(user.age, 30)
extension XCTestCase {
// 为了能够输出优雅的错误信息
// 遵循 LocallizedErrow
private struct RequireError<T>: LocalizedError {
let file: StaticString
let line: UInt
// 实现这个属性非常重要
// 否则测试失败时无法在记录中优雅地输出错误信息
var errorDescription: String? {
return "Required value of type \(T.self) was nil at line \(line) in file \(file)."
}
}
// 使用 file 和 line 能够自动捕获
// 源代码中出现的相对应的表达式
func require<T>(_ expression: @autoclosure () -> T?,
file: StaticString = #file,
line: UInt = #line) throws -> T {
guard let value = expression() else {
throw RequireError<T>(file: file, line: line)
}
return value
}
}
[UserServiceTests testLoggingIn] : failed: caught error: Required value of type User was nil at line 97 in file UserServiceTests.swift.
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/Forever_wj/article/details/120682068
内容来源于网络,如有侵权,请联系作者删除!