OCMock forward to original class method
Asked Answered
M

1

9

OCMock offers a nice syntax to mock class methods, but can class method calls be forwarded to the real class object?

self.connectionMock = [OCMockObject mockForClass:NSURLConnection.class];

[[[[self.connectionMock stub] andDo:^(NSInvocation *invocation) {
    NSURL *url = [invocation getArgumentAtIndexAsObject:2];
    NSLog(@"Passing through mock: %@", url);
} ] andForwardToRealObject] connectionWithRequest:OCMOCK_ANY delegate:OCMOCK_ANY];

The problem is andForwardToRealObject only works for partials. I could do the method swizzling myself, but is there an easy way for me to call the original class method using OCMock?

Macdougall answered 25/10, 2013 at 0:10 Comment(4)
Can you use a partial mock with a class instead of an object?Hertha
@JoshTheGeek Unfortunately a Class is not an NSObject so you can't create a partial mock on it. If you try to create a partial mock on an instance, it won't be able to forward the class method because it is not searching the class method selectors.Macdougall
Maybe there's a different approach. Can you explain more broadly what you're trying to test?Hetaera
I have to admit that I was not actually trying to test something in this case, at least not unit test. I am writing some code to capture NSURLConnection requests and responses - basically a passthrough. I thought it might be a one-liner with OCMock, but it hasn't been so bad just writing the method swapping code. It is possible, in general, that one would want to pass a class method call on to the real class method for much the same reasons as it can be handy with instance methods.Macdougall
F
0

Subclass OCMock and override forwardingTargetForSelector:(SEL)selector:

+(id)forwardingTargetForSelector:(SEL)selector
{
    Class yourClass = [classObject class];
    return yourClass;
}

(Credit: "How can I forward class methods in Objective-C?"

Faulkner answered 17/6, 2016 at 16:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.