pirishd / instantmock Goto Github PK
View Code? Open in Web Editor NEWCreate mocks easily in Swift
License: MIT License
Create mocks easily in Swift
License: MIT License
Hi,
Is there a way to know when some closure was called? Follow the example below:
func someFunction(success: @escaping SuccessClosure, failure: @escaping ErrorClosure) {
let apiUrl = ""
networkingProvider.get(apiUrl, success: success, failure: failure)
}
I made a mock of networkingProvider and I'd like knowing when the success closure was called. Follow the test example below:
func test_Example() {
repository.someFunction(success: Arg.closure(), failure: Arg.closure())
}
Is there a way to verify when success/failure closure is called?
@pirishd When trying to use Arg.eq with a dictionary, i.e.
Arg<[String: Any]>.eq(someDictionary)
the compiler throws this error: Ambiguous use of 'eq'
Is there anything I need to do in order for this to work ?
Thanks and great work on the library :)
I just have to set count: 0 ? Or is there any more intuitive way?
Thanks
Hello,
I'm excited to try InstantMock, but unfortunately I'm running into issues installing it in my project. I've created a new project using the swift package manager (4.2) and the issue I'm getting is this:
'foobar' /path/to/the/project: error: product dependency 'InstantMock' not found
warning: dependency 'InstantMock' is not used by any target
My Package.swift looks similar to this (I've removed my project's actual names, etc):
let package = Package(
name: "foobar",
dependencies: [
.package(url: "https://github.com/apple/swift-package-manager.git", from: "0.3.0"),
.package(url: "https://github.com/pirishd/InstantMock", from: "2.2.1")
],
targets: [
.target(name: "foobar", dependencies: [
"Utility"
]),
.testTarget(name: "foobarTests", dependencies: [
"foobar",
"InstantMock"
])
]
)
It's strange because it knows that "InstantMock" is a dependency, but when I have a target depend on it, swift seems to forget what it is.
Thoughts?
How could I test this method:
func get<T>(_ url: String, success: @escaping ((_ response: T?) -> Void), failure: @escaping ((_ errorMessage: String) -> Void)) where T: BaseMappable
Thanks
How could I execute a closure?
Error when running tests:
ld: '/Applications/Xcode 10.3.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/Frameworks/XCTest.framework/XCTest' does not contain bitcode. You must rebuild it with bitcode enabled (Xcode setting ENABLE_BITCODE), obtain an updated library from the vendor, or disable bitcode for this target. file '/Applications/Xcode 10.3.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/Frameworks/XCTest.framework/XCTest' for architecture arm64
Xcode 10.3.
Deployment Target 12.3
Swift 5
Podfile:
`target 'RecipePuppy' do
use_frameworks!
pod 'RxSwift'
pod 'RxCocoa'
pod 'SDWebImage'
target 'RecipePuppyUnitTests' do
use_frameworks!
inherit! :search_paths
pod 'InstantMock'
end
end`
I have to make some calls that may throw exceptions inside MockUsable equal method.
What do you think if we could add a Throw option on this method?
Thanks.
Can't use Arg.closure() for closure with single argument
Sometimes I receive a dictionary containing strings that are _NSContiguousString type. I don't know why. However, Verifier is not able to cast to MockUsable so as to compare.
Any tip?
How to do?
I'd like to have a block of setUp with some pre determined default expectations.
And I'd like to have an option to clear some pre determined one(s) at some test cases.
Is this a good idea? Is this worth it?
Thanks.
Do you have any solution for the case below?
AuthenticationSession extends Model. However, I need to make both of then implement MockUsable. Since you are using static var, its impossible to override..
extension AuthenticationSession_: MockUsable {
public static var any: AuthenticationSession_ {
let ret = AuthenticationSession_()
ret.id = "anyId"
return ret
}
public static var anyValue: MockUsable {
return self.any
}
public func equal(to value: MockUsable?) -> Bool {
guard let mock = value as? AuthenticationSession_ else { return false }
return self.id == mock.id
}
}
extension Model: MockUsable {
public static var any: Model {
let ret = Model()
return ret
}
public static var anyValue: MockUsable {
return self.any
}
public func equal(to value: MockUsable?) -> Bool {
guard let mock = value as? Model else { return false }
return false
}
}
How could I do that?
Let's suppose I have this:
mock.stub().call(
mock.bar(arg1: Arg.eq("hello"), arg2: Arg.any())
).andReturn(true)
However, its called twice. I would like to start returning true (first call) and finish returning false (second call).
Any tip?
XCode 10.2.1 (10E1001)
InstantMock (2.5.0)
I created a new XCode project and installed InstantMock via Cocoapods. My Podfile
is
platform :ios, '10.0'
use_frameworks!
target 'MyApp' do
target 'MyAppTests' do
pod 'InstantMock'
end
end
I created protocol with function that contains UInt
parameter
protocol DatabaseService {
func fetchMessages(count: UInt, completion: @escaping ([String]) -> ())
}
Because InstantMock does not support UInt
type by default, I added extension UInt+MockUsable
with target membership assigned to MyAppTests
target
extension UInt: MockUsable {
public static let any = 49
public static var anyValue: MockUsable {
return UInt.any
}
public func equal(to value: MockUsable?) -> Bool {
guard let uintValue = value as? UInt else { return false }
return self == uintValue
}
}
Then I created a simple test
func testThatControllerWillFetchMessagesOnAppearEvent() {
let controller = MessagesViewController()
let databaseServiceMock = DatabaseServiceMock()
controller.databaseService = self.databaseServiceMock
// when
controller.viewWillAppear(false)
// then
databaseServiceMock.expect().call(databaseServiceMock.fetchMessages(count: Arg.any(), completion: Arg.closure()))
}
class DatabaseServiceMock: Mock, DatabaseService {
func fetchMessages(count: UInt, completion: @escaping ([String]) -> ()) {
return super.call(count, completion)
}
}
But it falls with error
Fatal error: Unexpected type, only MockUsable types can be used with any: file Arg.swift, line 126
That I missed?
Thank you
Hi.
After swift 5 migration we faced a problem: expectations with dictionary arguments are not always working. According to the investigation the reason of that behaviour is a dictionary comparison algorithm. As keys array order is generally unpredictable the next test is failing floatly:
func testEqual_toWrongOrder() {
let dict1: [String: Any] = [
"foo": 1,
"bar": 2
]
let dict2: [String: Any] = [
"bar": 2,
"foo": 1
]
XCTAssertTrue(dict1.equal(to: dict2))
}
Hi faced an issue when writing an expectation like
objectUserMock .it .expect() .call(objectUserMock.useObject(Arg.eq(objectStub!)), count: 1)
will retain objectStub
inside ArgumentStorageImpl.instance
even after calling resetStubs
and resetExpectations
.
As a temporary workaround you may use objectUserMock.expect()
which will clear retained arguments
Here is an example repo which reproduce the issue https://github.com/vladislavsosiuk/InstantMockRetainArgumentIssue.
@pirishd Please let me know if you need more info
When I stub like this:
self.modelRepository.stub().call(
self.modelRepository
.beginTransaction(
options: Arg.any()
)
).andReturn(self.transaction)
How could I test this method:
func getManager<T>(managerType: T.Type) -> T where T:ManagerDelegate
Thanks.
I'm receiving this when I try to pass Arg.eq(nil) to a param that is 'Any?' type.
Any tip?
Hi, I'm trying to set an expectation for a static method by adding a static mock to the mock class so I can use it to use the call function in the static method
private static let mock = Mock()
static var it: Mock {
return mock
}
static func staticMethod(_ arg1:String?) {
mock.call(arg1)
}
and then in the test itself
mock.it.expect().call(mock.staticMethod("test")
But that generates this error :
Fatal error: Invalid argument configuration, see Arg class for more information
Is there a way to do achieve something like this ?
Is there any way to mock variables?
Suppose this class:
class Car {
var brand: String?
}
And I'd like to have a MockCar, which I could return my pre-determined brand.
Thanks.
I'm using PromiseKit, and I have methods like:
func doSomething() -> Promise<String> { ... }
How could I mock and stub so as to use .andReturn with "myString" for example?
Thanks
@pirishd Is there a way to make a typealias MockUsable ? I'm getting this message when I try to implement it :
Conformance of 'Dictionary<Key, Value>' to protocol 'MockUsable' conflicts with that stated in the protocol's module 'InstantMock' and will be ignored; there cannot be more than one conformance, even with different conditional bounds
How to do that since I cant make a protocol extends MockUsable?
Since I'm not able to make MyClass a MockUsable, is there any other way to check instead of using Arg.any() ? I tried Arg.verify ... However it also generates an exception.
I'd like to know why its not returning my response:
let response = ["data": "fake-data"]
self.connection.stub().call(
self.connection.post(
Arg.any()
)
).andReturn(response)
How to use self.call inside static methods?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.