Home > Software design >  How to override static class variable in swift
How to override static class variable in swift

Time:06-27

I need not use mock class for the unit testing in a project. But with Combine it's became little complicated. here is what I have done so far.

LocalFileManagerProtocol.swift

/// Protocol
protocol LocalFileManagerProtocol {
    associatedtype SharedType
    static var shared: SharedType { get }

    func getShared() -> SharedType
}

LocalFileManager.swift

/// for the production
final class LocalFileManager: LocalFileManagerProtocol {
    static var shared = LocalFileManager.init()
    typealias SharedType = LocalFileManager
    func getShared() -> LocalFileManager {
        Self.shared
    }
}

MockLocalFileManager.swift

/// for the test
struct MockLocalFileManager: LocalFileManagerProtocol {
    static var shared: MockLocalFileManager = MockLocalFileManager.init()
    
    func getShared() -> MockLocalFileManager {
        return MockLocalFileManager.shared
    }
    typealias SharedType = MockLocalFileManager
}

CalledClassForAll.swift

/// where the all classes called
struct CalledClassForAll {
    // In this line it gives error : Cannot assign like this
    static var localFileManager: LocalFileManagerProtocol = LocalFileManager.getShared()
}

/// extension for the tests
extension CalledClassForAll {

    public static func unit_test_override_dependencies() {
        // In here also can be assigned (override the type)
        CalledClassForAll.localFileManager = MockLocalFileManager.shared.getShared()
    }
}

I cannot use Generic type, because there are static variables and PassthroughSubject which I cannot change. Any help would be great.

CodePudding user response:

I fixed this issue and thank you for the comments. I update this as an answer may be this will help someone in the future.
Here is the code :

/// LocalFileManagerProtocol.swift

protocol LocalFileManagerProtocol {
    static var Shared: Self { get }
}

/// LocalFileManager.swift

final class LocalFileManager: LocalFileManagerProtocol {
    static var Shared: LocalFileManager = LocalFileManager.init()
    
}

/// MockLocalFileManager.swift

struct MockLocalFileManager: LocalFileManagerProtocol {
    static var Shared: MockLocalFileManager = MockLocalFileManager.init()

}

/// CalledClassForAll.swift

struct CalledClassForAll {
    static var FileManager: LocalFileManagerProtocol = LocalFileManager.Shared
}

/// extension for the unit tests

extension CalledClassForAll {

    public static func unit_test_override_dependencies() {
        CalledClassForAll.FileManager = MockLocalFileManager.Shared
    }
}
  • Related