-
Notifications
You must be signed in to change notification settings - Fork 12
/
PhotoRowViewModelTests.swift
89 lines (69 loc) · 2.28 KB
/
PhotoRowViewModelTests.swift
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
//
// PhotoRowViewModelTests.swift
// SwiftMVVMDemoTests
//
// Created by Rushi Sangani on 11/01/2024.
//
import XCTest
import Combine
@testable import SwiftMVVMDemo
final class PhotoRowViewModelTests: XCTestCase {
var viewModel: PhotoRowViewModel!
var cancellables: Set<AnyCancellable>!
override func setUpWithError() throws {
viewModel = PhotoRowViewModel(
imageLoader: MockAsyncImageLoader(),
cacheManager: MockCacheManager()
)
cancellables = []
}
override func tearDownWithError() throws {
viewModel = nil
cancellables = nil
}
func testImageDownloadAndCaching() {
let expectation1 = XCTestExpectation(description: "PhotoRowViewModel downloads image")
let expectation2 = XCTestExpectation(description: "PhotoRowViewModel caches image")
let imageUrl = "https://via.placeholder.com/150/d32776"
// verify initial state
XCTAssertNil(viewModel.image)
XCTAssertNil(viewModel.cacheManager.get(for: imageUrl))
viewModel.$image
.dropFirst()
.sink(receiveValue: { image in
expectation1.fulfill()
expectation2.fulfill()
})
.store(in: &cancellables)
// download
viewModel.downloadImage(url: imageUrl)
wait(for: [expectation1, expectation2], timeout: 2)
// verify
XCTAssertNotNil(viewModel.image)
XCTAssertNotNil(viewModel.cacheManager.get(for: imageUrl))
}
}
// MARK: - Mocks
class MockAsyncImageLoader: AsyncImageLoading {
private let sampleImage = UIImage(named: "sample.png")!
func downloadWithCombine(url: String) -> AnyPublisher<UIImage, Error> {
Just(sampleImage)
.setFailureType(to: Error.self)
.eraseToAnyPublisher()
}
func downloadWithAsync(url: String) async throws -> UIImage {
sampleImage
}
}
class MockCacheManager: Cacheable {
private var cache: Dictionary<String, UIImage> = [:]
func get(for url: String) -> UIImage? {
cache[url]
}
func set(_ image: UIImage?, for url: String) {
cache[url] = image
}
func clear() {
cache.removeAll()
}
}