IOS

Swift: Why You Shouldn’t Make Mock Classes Public for Tests

Because you’ll run into weird access control problems.

For example, you may be setting a public property of a class, be po logging the new value out in console no problem, and still be getting the old value in expecting tests, right in the next line.

Instead of this:

public class MockCat: RealCat {
    public var meowCalled: Bool = false
    
    public override func meow() {
        meowCalled = true
    }
}

Just do a normal non-public class, and use the @testable keyword for importing this mock module so that all its properties are naturally accessible:

@testable import mock_cat

class CatTests: QuickSpec {
  override class func spec() {
    describe("testing the mock cat, so we do no harm to the real thing")
  }
}

Standard

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.