This library is work in progress, only bare minimum is provided from OCMockito.
OCMockito adapter for Swift, that allows to create and operate on mocks which are subclasses for NSObject
.
The adapter comes with two files:
OCMockitoSwiftAdapter.{h,m}
-- Objective-C code to provide Swift friendly interface that allows mocking, veryfing and stubbingOCMockito.swift
-- set of global functions for Swift, e.g.mock()
orverify()
Simply add to your Podfile
:
pod 'OCMockitoSwift', '~> 0.3'
Simply add to your Cartfile
:
github "azubala/OCMockitoSwift"
To create a mock of an NSObject
subclass simply call:
let mock = mock(MyObject.self) // no casting needed
To create a mock of an Objective-C protocol that extends NSObject
protocol you execute the following:
let mock = mockProtocol(MyProtocol.self) as? MyProtocol // casting required :(
To verify if there were interaction with the mock you use the verify
global function:
verify(mock) { #selector(MyObject.doSomethingNoArguments) } // method without arguments
verify(mock) { (#selector(MyObject.doSomething(with:)), arguments: ["Foo"]) } // method with arguments
To verify count of the mock interaction simply use count
parameter (by default it's set to 1). For example to verify that there were no interactions with mock you can simply call:
verify(testMock, count: 0) { #selector(TestClass.doSomethingNoArguments) }
Working with OCHamcrest matchers:
// provide map of matchers for each argument index; `whatever()` is equivalent of `anything()`
verify(testMock) { (#selector(TestClass.doSomething(with:)), matchers: [0: whatever()]) }
// Capturing arguments
var captor = HCArgumentCaptor()
verify(testMock) { (#selector(TestClass.doSomething(with:)), matchers: [0: captor]) }
var capturedValue = captor.value as! String
expect(capturedValue).to(equal("Bar"))
To stub return value of a particular method from mock you use the given
global function:
given(mock) { (#selector(MyObject.returnObjectMethodNoArguments), willReturn: "Fake Value")} // method without arguments
given(mock) { (#selector(MyObject.returnSomething(with:)), arguments: ["Foo"], willReturn: "Fake Value")} // method with arguments
To stub using closure use willDo:
parameter:
given(testMock) { (#selector(MyObject.returnIntegerMethodNoArguments), willDo: { _ in
return 42
})}
Aleksander Zubala | zubala.com
OCMockitoSwift is available under the MIT license. See the LICENSE file for more info.