OCMockito capturing primitive types?

2019-03-31 14:21发布

问题:

How do I use OCMockito to capture argument with primitive values?

MKTArgumentCaptor seems to be able to capture only object types? Xcode says "Incompatible pointer to integer conversion".

回答1:

For primitive arguments, you have to do a little dance. Let's say we mocked NSMutableArray and wanted to verify calls to

- (void)replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;

Instead of

[verify(mockArray) replaceObjectAtIndex:[argument capture] withObject:anything()];

which gives you the type conflict, we just have a dummy value (0 will do fine) but add an OCMockito call to override the matcher at a given argument index:

[[verify(mockArray) withMatcher:[argument capture] forArgument:0]
    replaceObjectAtIndex:0 withObject:anything()];

The argument index for -withMatcher:forArgument: is 0-based for the first argument, so this says, "For the first argument, ignore whatever was passed in and use this matcher instead."

There is also a method -withMatcher: which just does this on the first argument, so this example could be simplified to

[[verify(mockArray) withMatcher:[argument capture]]
    replaceObjectAtIndex:0 withObject:anything()];


标签: ocmockito