Чтобы понять разницу между expectation(forNotification:, object:, handler:)
и expectation(description:)
, я создал простой подкласс XCTestCase
с помощью Swift 3.
Здесь мы хотим проверить, что BlockOperation
, который публикует Notification
, обновляет указанное свойство Int?
нашего класса с запрошенным значением 50.
1. Использование expectation(description:)
с addObserver(_:, selector:, name:, object:)
import XCTest
class AppTests: XCTestCase {
var testExpectation: XCTestExpectation?
var finalAmount: Int?
func testFinalAmount() {
let notificationName = Notification.Name(rawValue: "BlockNotification")
// Set self as an observer
let selector = #selector(updateFrom(notification:))
NotificationCenter.default.addObserver(self, selector: selector, name: notificationName, object: nil)
// Set expectation
testExpectation = expectation(description: "Did finish operation expectation")
// Set and launch operation block and wait for expectations
let operation = BlockOperation(block: {
NotificationCenter.default.post(name: notificationName, object: nil, userInfo: ["amount": 50])
})
operation.start()
waitForExpectations(timeout: 3, handler: nil)
// Asserts
XCTAssertNotNil(finalAmount)
XCTAssertEqual(finalAmount, 50)
}
func updateFrom(notification: Notification) {
if let amount = notification.userInfo?["amount"] as? Int {
self.finalAmount = amount
}
self.testExpectation?.fulfill()
}
}
2. Использование expectation(description:)
с addObserver(forName:, object:, queue:, using:)
import XCTest
class AppTests: XCTestCase {
var finalAmount: Int?
func testFinalAmount() {
let notificationName = Notification.Name(rawValue: "BlockNotification")
// Set expectation
let testExpectation = expectation(description: "Did finish operation expectation")
// Set self as an observer
let handler = { (notification: Notification) -> Void in
if let amount = notification.userInfo?["amount"] as? Int {
self.finalAmount = amount
}
testExpectation.fulfill()
}
NotificationCenter.default.addObserver(forName: notificationName, object: nil, queue: nil, using: handler)
// Set and launch operation block and wait for expectations
let operation = BlockOperation(block: {
NotificationCenter.default.post(name: notificationName, object: nil, userInfo: ["amount": 50])
})
operation.start()
waitForExpectations(timeout: 3, handler: nil)
// Asserts
XCTAssertNotNil(finalAmount)
XCTAssertEqual(finalAmount, 50)
}
}
3. Использование expectation(forNotification:, object:, handler:)
import XCTest
class AppTests: XCTestCase {
var finalAmount: Int?
func testFinalAmount() {
let notificationName = Notification.Name(rawValue: "BlockNotification")
// Set expectation
let handler = { (notification: Notification) -> Bool in
if let amount = notification.userInfo?["amount"] as? Int {
self.finalAmount = amount
}
return true
}
expectation(forNotification: notificationName.rawValue, object: nil, handler: handler)
// Set and launch operation block and wait for expectations
let operation = BlockOperation(block: {
NotificationCenter.default.post(name: notificationName, object: nil, userInfo: ["amount": 50])
})
operation.start()
waitForExpectations(timeout: 3, handler: nil)
// Asserts
XCTAssertNotNil(finalAmount)
XCTAssertEqual(finalAmount, 50)
}
}
tl;dr
Использование expectation(forNotification: String, object:, handler:)
вместо expectation(description:)
в нашем тестовом примере дает некоторые преимущества:
- наш тест теперь требует меньше строк кода (31 вместо 35 или 37 строк),
- наш тест больше не требует использования
addObserver(_:, selector:, name:, object:)
с #selector
или addObserver(forName:, object:, queue:, using:)
,
- наш тест больше не требует объявлять экземпляр
XCTestExpectation
как свойство нашего класса или как переменную области действия нашего тестового метода и помечать его как встречающийся в какой-то момент с fulfill()
.
person
Imanou Petit
schedule
24.08.2016