NSHipster touches on language features in Swift which make an external mocking library less necessary:

In Swift, classes can be declared within the definition of a function, allowing for mock objects to be extremely self-contained. Just declare a mock inner-class, override and [sic] necessary methods:

func testFetchRequestWithMockedManagedObjectContext() {
    class MockNSManagedObjectContext: NSManagedObjectContext {
        override func executeFetchRequest(request: NSFetchRequest!, error: AutoreleasingUnsafePointer<NSError?>) -> [AnyObject]! {
            return [["name": "Johnny Appleseed", "email": "[email protected]"]]
        }
    }

    ...
}

The ability to create a subclass of your external dependency in the local scope plus the addition of XCTestExpectation solve a lot of the same problems as OCMock.

The one thing that a library such as OCMock provides that is very useful are its "verify" methods to ensure that the mock classes were called. It's possible to manually add this, but the automatic addition is nice.


I create my mock classes by wrapping everything in a protocol. I hand roll a mock class to conform to the protocol in question, like so:

protocol Dog: class {
    var name: String { get }

    func bark()
}

class DogImpl: Dog {
    var name: String

    init(name: String) {
        self.name = name
    }

    func bark() {
        print("Bark!")
    }
}

class DogMock: Dog {
    var name = "Mock Dog"
    var didBark = false

    func bark() {
        didBark = true
    }
}

I use this in conjunction with dependency injection to achieve full test coverage. It's a lot of boilerplate, but I haven't had any issues with this approach so far.

Regarding subclass mocking, you'll run into trouble with final classes, or if they have non-trivial initializers.


I want to point something in addition to marked answer - I do not know whether it's a bug or not.

If you subclass NSObject somehow(in my case I was subclassing UIView which internally subclass NSObject) you need to declare overriden function explicity with @objc otherwise your test wont compile. In my case the compiler itself crashes with following:

Segmentation Fault: 11

So the following class:

public class ClassA: UIView
{
    @objc public func johnAppleseed() {

    }
}

Should be unit tested the following way:

class ClassATests: XCTestCase {

    func testExample()
    {
        class ClassAChildren: ClassA
        {
            @objc private override func johnAppleseed() {

            }
        }
    }
}