Brightify / Cuckoo

Boilerplate-free mocking framework for Swift!
MIT License
1.67k stars 174 forks source link

How to mock ProcessInfo? #375

Closed xareelee closed 2 years ago

xareelee commented 3 years ago

I want to make ProcessInfo.processInfo.environment[key] return specific values when testing.

How can I achieve that with Cuckoo? It's hard to find a sample code. Most of them use dependency injection with adopting protocols.

MatyasKriz commented 3 years ago

Hey, @xareelee. Cuckoo depends on having the source code on hand to generate the mocking classes as needed. ProcessInfo might be mockable using the OCMock integration, so take a look at the tests and try that.

mugabe commented 3 years ago

You can do it in swifty way without OCMock.

At first, to keep your code testable you should not use ProcessInfo.processInfo directly, but pass it as dependency to your class. e.g.:

class App {
    init(processInfo: ProcessInfo) {
        if (processInfo.environment["help"] != nil) {
            printHelp()
        }
    }
}
App(processInfo: ProcessInfo.processInfo)

Then you can describe your own protocol that ProcessInfo should conform.

protocol ProcessInfoProtocol {
    var environment: [String : String] { get }
}
extension ProcessInfo: ProcessInfoProtocol { }

Now you can replace dependency type of your class to ProcessInfoProtocol and pass own implementation or Cuckoo's mock.