Parcourir la source

Fix a crash when trying to access KingfisherWrapper<UIApplication>.shared in a Unit Test

Max Chuquimia il y a 2 mois
Parent
commit
d157b52626
2 fichiers modifiés avec 11 ajouts et 2 suppressions
  1. 2 1
      Sources/Cache/ImageCache.swift
  2. 9 1
      Tests/KingfisherTests/ImageCacheTests.swift

+ 2 - 1
Sources/Cache/ImageCache.swift

@@ -1292,7 +1292,8 @@ extension KingfisherWrapper where Base: UIApplication {
     public static var shared: UIApplication? {
         let selector = NSSelectorFromString("sharedApplication")
         guard Base.responds(to: selector) else { return nil }
-        return Base.perform(selector).takeUnretainedValue() as? UIApplication
+        guard let unmanaged = Base.perform(selector) else { return nil }
+        return unmanaged.takeUnretainedValue() as? UIApplication
     }
 }
 #endif

+ 9 - 1
Tests/KingfisherTests/ImageCacheTests.swift

@@ -895,7 +895,15 @@ class ImageCacheTests: XCTestCase {
         let result = try XCTUnwrap(fileURL)
         XCTAssertTrue(result.absoluteString.hasSuffix(".myExt"))
     }
-    
+
+#if !os(macOS) && !os(watchOS)
+    func testKingfisherWrapperUIApplicationSharedReturnsNilInUnitTest() {
+        // UIApplication.shared is not available in some Unit Tests contexts.
+        // This tests that accessing it via KingfisherWrapper does not cause a crash.
+        XCTAssertNil(KingfisherWrapper<UIApplication>.shared)
+    }
+#endif
+
     // MARK: - Helper
     private func storeMultipleImages(_ completionHandler: @escaping () -> Void) {
         let group = DispatchGroup()