sabirvirtuoso / Mockit

A simple mocking framework for Swift, inspired by the famous http://mockito.org/
MIT License
120 stars 27 forks source link

How to stub the same method twice with different arguments #18

Open matvdg opened 6 years ago

matvdg commented 6 years ago

Hi, I need to stub the same method of my mockObject twice, but I can't use the variadic thenReturn because it's a generic method returning different types Single<T.Data> according to the T provided as an argument. (In the code above a Query is a protocol, and the method getSingle<T>(query: T) -> Single<T.Data> where T : Query accepts any class that implements query and returns a Single of type T.Data)

let _ = self.mockDataSource.when().call(withReturnValue: self.mockDataSource.getSingle(query: QueryA())) .thenReturn(Single.just(payloadA))

let _ = self.mockDataSource .when().call(withReturnValue: self.mockDataSource.getSingle(query: QueryB())) .thenReturn(Single.just(payloadB))

However, the second stub is never called, always the first one, and my tests fail. I'd like to have the ability to create a stub returning a specific type according to the type provided as an argument, either by matching the provided type (I failed to do it with ArgumentMatcher) either by specifying the order...

Thank you for your help,

sabirvirtuoso commented 6 years ago

Hi,

As of now this feature is not yet included in the current Mockit implementation. Please feel free to contribute if you want and send me a PR.

Thanks.

Nicolas-Trutet commented 6 years ago

Hi, I ran into the same issue. We were trying to stub the same method multiple times but only once in every different test methods. The issue here is that your mocked object keep the same context for every tests. Because Mockit does not provide any feature to stop the mocked object, the solution is to create different mock objects for every test scenarios.

Hope it helps.