I am staring to use OCMockito for Unit Testing. Right now I am using it to mock a UserDefaults
(through dependency injection).
I can control what is returned back by:
[given([mockUserDefaults objectForKey:@"some key"]) willReturn:@"a value I want"];
Now my question is: How do I check what values the user set to the mock UserDefaults
?
for example, if user issued:
[self.userDefaults setObject:[NSDate date] forKey:"example"];
How do I get the date
back from the mock userDefaults
?
OCMockito doesn't have a way (yet) to capture and return arguments. Instead, each argument must satisfy an OCHamcrest matcher. If no matcher is specified, then equalTo
is assumed.
Testing [NSDate date]
is generally not a good idea in unit tests, because you have no control over the date. But for the sake of example, here's a verification that the argument is any NSDate. (sut
is the "system under test".)
[verify(sut.userDefaults) setObject:instanceOf([NSDate class]) forKey:@"example"];
So here, the first matcher is instanceOf
to match any NSDate.
The second matcher is implicitly equalTo(@"example)
Update:
OCMockito 1.1.0 has a way to capture arguments, using MKTArgumentCaptor:
MKTArgumentCaptor *argument = [[MKTArgumentCaptor alloc] init];
[verify(sut.userDefaults) setObject:[argument capture] forKey:@"example"];
You can retrieve the captured argument with [argument value]
, or an array of all captured arguments with [argument allValues]
.