I'm trying to mock a call to NSURLConnection. I swizzle the class method call with my own that calls my mock object. I'm trying to implement the mock like this:
[[[[urlConnectionMock expect] andDo:^(NSInvocation *invocation) {
NSURLResponse * __autoreleasing *responsePointer;
[invocation getArgument:&responsePointer atIndex:3];
id response = [OCMockObject niceMockForClass:NSHTTPURLResponse.class];
[[[response stub] andReturnValue:OCMOCK_VALUE((NSInteger){ 200 })] statusCode];
*responsePointer = response;
}] andReturn:encryptedResponse] sendSynchronousRequest:OCMOCK_ANY returningResponse:OCMOCK_ANY error:OCMOCK_ANY];
The problem is that OCMOCK_ANY is an Objective-C pointer, not a pointer to a pointer (the compiler rightly complains). Before I dig more deeply into the OCMock source, perhaps someone can suggest how to get around this? Full credit given if you have a better approach entirely.
Figured it out. By-reference is already built into OCMock.
id fakeResponse = [OCMockObject niceMockForClass:NSHTTPURLResponse.class];
[[[fakeResponse stub] andReturnValue:OCMOCK_VALUE((NSInteger){ 200 })] statusCode];
[[[urlConnectionMock expect] andReturn:encryptedResponse] sendSynchronousRequest:OCMOCK_ANY returningResponse:[OCMArg setTo:fakeResponse] error:[OCMArg setTo:nil]];
This is so much happier looking as well!
Related
I have a method I would like to test with OCMock but not sure how to do that. I need to mock
ExtClass which isn't defined as part of my code (external library):
+(NSString *)foo:(NSString *)param
{
ExtClass *ext = [[ExtClass alloc] initWithParam:param];
if ([ext someMethod])
return #"A";
else
return #"B";
}
Thanks in advance!
OCMock 2
id mock = [OCMockObject mockForClass:[ExtClass class]];
// We stub someMethod
BOOL returnedValue = YES;
[[[mock stub] andReturnValue:OCMOCK_VALUE(returnedValue)] someMethod];
// Here we stub the alloc class method **
[[[mock stub] andReturn:mock] alloc];
// And we stub initWithParam: passing the param we will pass to the method to test
NSString *param = #"someParam";
[[[mock stub] andReturn:mock] initWithParam:param];
// Here we call the method to test and we would do an assertion of its returned value...
[YourClassToTest foo:param];
OCMock3
// Parameter
NSURL *url = [NSURL URLWithString:#"http://testURL.com"];
// Set up the class to mock `alloc` and `init...`
id mockController = OCMClassMock([WebAuthViewController class]);
OCMStub([mockController alloc]).andReturn(mockController);
OCMStub([mockController initWithAuthenticationToken:OCMOCK_ANY authConfig:OCMOCK_ANY]).andReturn(mockController);
// Expect the method that needs to be called correctly
OCMExpect([mockController handleAuthResponseWithURL:url]);
// Call the method which does the work
[self.myClassInstance authStarted];
OCMVerifyAll(mockController);
Notes
Ensure that in both cases you stub two methods (alloc and the init... method). Also, make sure that both stubbing calls are made on the instance of the class mock (not the class itself).
Docs: Class methods section in the OCMock features
Alternatives
This (strange)solution may be useful in case you want to test legacy code that due to whatever reason you cannot refactor. However, if you can modify the code you should refactor it and get an ExtClass object as a parameter, not a string, delegating the creation of ExtClass out of that method. Your production and test code would be simpler and clearer, specially in a more complex real life case, not in this simple example.
in my fixture setUp i have the following
-(void)setUp{
_vc = [OCMockObject partialMockForObject:[[InboxViewController alloc] init]];
//stub out the view stuff
[[_vc stub] removeTask:OCMOCK_ANY];
[[_vc stub] insertTask:OCMOCK_ANY];
}
There are 15 tests in the fixture, however, I need to actually test that those 2 methods are invoked, so I wrote 2 tests
-(void)someTest{
[[_vc expect] removeTask:OCMOCK_ANY];
[_vc removeAllTasksFromList:taskList notInList:newTaskList];
[_vc verify];
}
but that test fails
i also tried
-(void)someTest{
[[_vc stopMocking];
[[_vc expect] removeTask:OCMOCK_ANY];
[[_vc stub] removeTask:OCMOCK_ANY];
[_vc removeAllTasksFromList:taskList notInList:newTaskList];
[_vc verify];
}
But the test still fails. Am I missing something, or is this just how OCMock works?
The only way I can make it work is like this
-(void)someTest{
//re create and init the mock object
_vc = [OCMockObject partialMockForObject:[[InboxViewController alloc] init]];
[[_vc expect] removeTask:OCMOCK_ANY];
[[_vc stub] removeTask:OCMOCK_ANY];
[_vc removeAllTasksFromList:taskList notInList:newTaskList];
[_vc verify];
}
Maybe the documentation should be clearer. What stopMocking does for a partial mock is to restore the real object, in your case the InboxViewController, to its original state. Calling stopMocking does not reset the mock object, which means it does not clear the stubs and expectations. You can always call stopMocking and then create a new mock for the same real object.
As was pointed out in another answer, stubbing and expecting the same method is generally better avoided, but if you have to do it, make sure to set up the expect before the stub; otherwise the stub will handle the invocations and the expect will never see them.
I know that traditionally many people recommend to use the setup method to set up the test subject. My personal experience, over the years, is that it's generally not worth it. Saving a couple of lines in each test might look attractive but in the end it does create coupling between the individual tests, making the suite more brittle.
Seems that you need to create a new mock to expect a method that you already stubbed.
I would recommend you to reconsider to use a partial mock in all your test cases, and if you want so, extract this:
[[_vc stub] removeTask:OCMOCK_ANY];
[[_vc stub] insertTask:OCMOCK_ANY];
into a helper method and call that method from the tests you really need it, removing it from your setUp method.
And, small tip :), you should call [super setUp] at the beginning of your setUp implementation.
You can do the following to remove stubs from an OCMockObject, which will enable you to keep the stub code in your -(void)setUp, but still allow you to add an expect in a later test.
Add the following category to your test to return the OCMockObject ivar.
#interface OCMockObject (Custom)
- (void)removeStubWithName:(NSString*)stubName;
#end
#implementation OCMockObject (Custom)
- (void)removeStubWithName:(NSString*)stubName {
NSMutableArray* recordersToRemove = [NSMutableArray array];
for (id rec in recorders) {
NSRange range = [[rec description] rangeOfString:stubName];
if (NSNotFound == range.location) continue;
[recordersToRemove addObject:rec];
}
[recorders removeObjectsInArray:recordersToRemove];
}
#end
Example usage:
Make sure you remove the stub for a method BEFORE you add the expect.
-(void)someTest{
[_vc removeStubWithName:#"removeTask"];
[[_vc expect] removeTask:OCMOCK_ANY];
[_vc removeAllTasksFromList:taskList notInList:newTaskList];
[_vc verify];
}
This will allow your test to run as you expect.
It's a useful hack, at least until the OCMock developers allow this functionality.
A couple of things to note:
You should keep a reference to the actual object you're mocking. Invoke mock setup/verification on the mock reference, and methods you're testing on the actual object.
You shouldn't stub and expect the same method call. The stub will match, and the expectation won't pass.
I'm assuming you're stubbing in setUp because you have some methods that may or may not be called in the tests. If so, you can structure your tests like this:
static InboxViewController *_vc;
static id mockInbox;
-(void)setUp{
_vc = [[InboxViewController alloc] init];
mockInbox = [OCMockObject partialMockForObject:_vc];
//stub out the view stuff
[[mockInbox stub] removeTask:OCMOCK_ANY];
[[mockInbox stub] insertTask:OCMOCK_ANY];
}
-(void)someTest{
[[mockInbox expect] somethingIExpectForThisTest:OCMOCK_ANY];
[_vc removeAllTasksFromList:taskList notInList:newTaskList];
[mockInbox verify];
}
-(void)someOtherTest{
[[mockInbox expect] someOtherThingIExpectForThisTest:OCMOCK_ANY];
[_vc doSomethingElse];
[mockInbox verify];
}
The order in which the stub and expect calls are given is important to the partial mock. Stubbing the method before expecting it will mean that any messages sent to the stubbed method will never meet the expectation.
On the other hand, stopMocking just means the partial mock will stop being associated to the real object. The mock still keeps its recorders (stubs and expectations) and works as usual. You can verify this by sending removeAllTasksFromList:notInList to your real object, which in this case is not assigned to any variable. You'll see in this case that the message does reach your object's implementation. The mock will still fail the verify call, though. In general, you should be calling methods on your real object. The partial mock will still intercept the messages.
As mentioned in the other answer, the best way around this is to create a new partial mock and call expect before stubbing the method. You could even implement a helper:
- (void) setUpPartialMockWithExpect:(BOOL)needExpect {
_vc = [OCMockObject partialMockForObject:[[InboxViewController alloc] init]];
if( needExpect )
[[_vc expect] removeTask:OCMOCK_ANY];
//stub out the view stuff
[[_vc stub] removeTask:OCMOCK_ANY];
[[_vc stub] insertTask:OCMOCK_ANY];
}
And call that in each of your -(void)test...
So I have a class I wrote some test cases for. This class has these two methods:
- (void)showNextNewsItem {
self.xmlUrl = self.nextNewsUrl;
[self loadWebViewContent];
}
- (void)showPreviousNewsItem {
self.xmlUrl = self.previousNewsUrl;
[self loadWebViewContent];
}
Could be refactored and this is quite primitive, but nevertheless I just want to make sure next loads next and previous loads previous. So I use OCMock to instantiate a OCMockObject for my SUT class like this:
- (void)testShowNextOrPreviousItemShouldReloadWebView {
id mockSut = [OCMockObject mockForClass:[NewsItemDetailsViewController class]];
[[[mockSut expect] andReturn:#"http://www.someurl.com"] nextNewsUrl];
[[mockSut expect] loadWebViewContent];
[[[mockSut expect] andReturn:#"http://www.someurl.com"] previousNewsUrl];
[[mockSut expect] loadWebViewContent];
[mockSut showNextNewsItem];
[mockSut showPreviousNewsItem];
[mockSut verify];
}
The problem lies in the two lines actually calling the methods that do something to be verified. OCMock now tells me, that invoking showNextNewsItem and showPreviousNewsItem are not expected. Of course, it's not expected because I am in the test and I only expect certain things to happen in the production code itself.
Which part of the mocking concept didn't I understand properly?
It's generally confusing to mock the class under test, but if you want to do that, you need a "partial mock", so that you can call methods without stubbing them and have them execute the normal methods.
This appears to be supported in OCMock according to the docs.
I found the solution. Using a partialMock on the object does exactly what I want. This way, calls I explicitly define are mocked and I call the methods that are under test on the "not-mocked" object.
- (void)testShowNextOrPreviousItemShouldReloadWebView {
NewsItemDetailsViewController *sut = [[NewsItemDetailsViewController alloc] init];
id mockSut = [OCMockObject partialMockForObject:sut];
[[[mockSut expect] andReturn:#"http://www.someurl.com"] nextNewsUrl];
[[mockSut expect] loadWebViewContent];
[[[mockSut expect] andReturn:#"http://www.someurl.com"] previousNewsUrl];
[[mockSut expect] loadWebViewContent];
[sut showNextNewsItem];
[sut showPreviousNewsItem];
[mockSut verify];
}
I have some code I want to test that is passing around the address of a struct:
MyObject myObject = ...;
MyRecord record = [someObject record]; //record is a #property
[myObject add:&record];
I've mocked someObject to return a record:
MyRecord record = ...;
[[[_mockSomeObject stub] andReturnValue:OCMOCK_VALUE(record)] record];
[[_mockMyObject expect] add:&record];
Unfortunately, OCMock fails (I believe) because pulling the struct out of the NSValue wrapper will always return a different address.
Is there a way to get an expectation to work correctly if one of the parameters is an address of a struct?
Look at this post on returning structs with OCMock. Looks like the OCMOCK_VALUE macro just won't cut it.
I'm trying to mock a method that has the equivalent of the following signature:
- (NSDictionary *) uploadValues:(BOOL)doSomething error:(NSError **)error
I want it to return a small dictionary so that my test can make sure the code uses the dictionary properly. however, no matter what i do OCMock always returns nil from the method, regardless of how i stub it out. The error begins as nil in the code i'm testing, and these are the different ways i've tried stubbing it:
NSError * error = nil;
[[[mock stub] andReturn:someDict] uploadValues:YES error:&error];
[[[mock stub] andReturn:someDict] uploadValues:YES error:nil];
[[[mock stub] andReturn:someDict] uploadValues:YES error:[OCMArg any]];
and none of them work. Does OCMock support handles as stubbed message arguments and if so, what's the correct way to do it?
[[[mock stub] andReturn:someDict] uploadValues:YES error:[OCMArg setTo:nil]];
or
NSError* someError = ...
[[[mock stub] andReturn:someDict] uploadValues:YES error:[OCMArg setTo:someError]];
You could also do
[[[mock stub] andReturn:someDict] uploadValues:YES error:[OCMArg anyPointer]];
but this might cause your code to incorrectly think that you passed back a real NSError.
With ARC, your method declaration will probably look like this:
- (NSDictionary *) uploadValues:(BOOL)doSomething error:(NSError *__autoreleasing *)error;
Here is how I mock these types of methods:
BOOL mockDoSomething = YES;
NSError __autoreleasing *error = nil;
[[[mock stub] andReturn:someDict] uploadValues:OCMOCK_VALUE(mockDoSomething) error:&error];
NSError *__autoreleasing *err = (NSError *__autoreleasing *) [OCMArg anyPointer];
[[[_mockReporter stub] andReturnValue:OCMOCK_VALUE((BOOL){YES})]
yourMethodCall:err];
I created a category on OCMArg to aid with this situation.
OCMArg+Helpers.h:
#interface OCMArg (Helpers)
+ (NSError *__autoreleasing *)anyError;
#end
OCMArg+Helpers.m:
#implementation OCMArg (Helpers)
+ (NSError *__autoreleasing *)anyError {
return (NSError *__autoreleasing *)[OCMArg anyPointer];
}
#end
Then, whenever I have an error param I need to mock, use anyError, like so:
[[myMock stub] someMethodWithArg:anArg error:[OCMArg anyError]];
Sadly, I haven't found a good solution for this either. The best I can say is to try to make the use of the NSError** as small as possible, and then put it in an isolated function that you can completely mock out on your partial mock.
I'm finding that any code that uses anything other than an NSObject* (or derived) or primitive values (NSInteger, BOOL, etc) is pretty much impossible to test using OCMock.