1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
protocol NetworkService {
func fetchData(completion: @escaping (Data?) -> Void)
}
class MockNetworkService: NetworkService {
var dataToReturn: Data?
func fetchData(completion: @escaping (Data?) -> Void) {
completion(dataToReturn)
}
}
class DataFetcher {
let networkService: NetworkService
init(networkService: NetworkService) {
self.networkService = networkService
}
func fetchData(completion: @escaping (Data?) -> Void) {
networkService.fetchData(completion: completion)
}
}
// 单元测试
func testFetchDataReturnsExpectedData() {
let mockService = MockNetworkService()
mockService.dataToReturn = Data("Test data".utf8)
let dataFetcher = DataFetcher(networkService: mockService)
dataFetcher.fetchData { data in
assert(data == mockService.dataToReturn)
}
}
Post
CanceliOS开发--DI和单元测试
This post is licensed under CC BY 4.0 by the author.