ilan
ilan

Reputation: 4462

How to unit test a function without a return value

I have a wrapper for the log system that adds some functionality like remote logging.

The functions are class functions and they don't return a value they just print to the log and call a delegate method.

I want to unit test that each function calls the right delegation method, but the methods dont return any value. so is there any way to test this?

Thanks

Upvotes: 0

Views: 2603

Answers (2)

Zafer Sevik
Zafer Sevik

Reputation: 191

Try creating a Logger protocol to implement RealLogger and MockLogger

protocol Logger {
    func log(string: String)
}

class RealLogger: Logger {
    func log(string: String) {
        print(string)
    }
}

class MockLogger: Logger {
    var isLogCalled = false
    var logStringParameter:String? = nil

    func log(string: String) {
        isLogCalled = true
        logStringParameter = string
    }
}

Since you have a class with a class function you need to have a static var reference to replace it while testing

class MyClass {
    private static var logger: Logger? = RealLogger()

    class func setLogger(logger: Logger) {
        self.logger = logger
    }

    class func logAndCallDelegate() {
        logger?.log(string: "my log message")
        // delegate call
    }
}

Change your real logger and use the mock for testing

class MyClassTests: XCTestCase {
    var logger: MockLogger!

    override func setUp() {
        super.setUp()
        logger = MockLogger()
        MyClass.setLogger(logger: logger)

        MyClass.logAndCallDelegate()
    }

    func testLogger() {
        XCTAssertTrue(logger.isLogCalled)
        XCTAssertEqual(logger.logStringParameter, "my log message")
    }

}

You can apply the same approach to test the delegate call.

If you don't want to instantiate RealLogger in MyClass you can use a LoggerLocator object to supply RealLogger and change the logger implementation in LoggerLocator while testing.

Upvotes: 2

Durdu
Durdu

Reputation: 4849

Try to use

readline()

Also you could create a fake delegate to test for the callback.

Upvotes: 0

Related Questions