How do you mock out private properties with OCMock for iOS?
Asked Answered
V

2

18

I have a private property that is declared in the .m file of my class to be tested, let's call it ClassUnderTest. ClassUnderTest instantiates an instance of ClassToBeMocked. How do I use OCMock to mock out an instance of the ClassToBeMocked and assign it to the ClassUnderTest?

Vasiliki answered 9/8, 2012 at 23:37 Comment(1)
Possible duplicate of #35071Avigdor
B
51

Re-declare the property in your test class. You can do the same for private methods. In ClassUnderTestTest.m:

@interface ClassUnderTest ()

@property(retain)ClassToBeMocked *instanceToBeMocked;

-(void)somePrivateMethod;

@end
Boozy answered 10/8, 2012 at 16:59 Comment(2)
Thank you! This is beautiful. I totally forgot about that aspect of Objective-C ;-)Vasiliki
@abellina no you can't currently mock class methods with OCMockBoozy
G
1

Does the following work?

id classUnderTest = ... // get from somewhere
id mock = [OCMockObject mockForClass:[ClassToBeMocked class]];
[classUnderTest setValue:mock forKey:@"nameOfThatPrivateProperty"];

Not totally sure whether you can set private properties like this. I think it depends on what kind of property it is.

Gust answered 10/8, 2012 at 11:4 Comment(2)
Can you get properties like this as well?Exoteric
Yes - this is just using KVC within the Foundation framework. See here: developer.apple.com/library/mac/documentation/Cocoa/Conceptual/…Kerns

© 2022 - 2024 — McMap. All rights reserved.