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?
Asked
Active
Viewed 7,651 times
18

vikingosegundo
- 52,040
- 14
- 137
- 178

Shiun
- 2,677
- 1
- 20
- 20
-
Possible duplicate of https://stackoverflow.com/questions/34571/how-do-i-test-a-class-that-has-private-methods-fields-or-inner-classes – Raedwald Dec 14 '17 at 13:02
2 Answers
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

Christopher Pickslay
- 17,523
- 6
- 79
- 92
-
Thank you! This is beautiful. I totally forgot about that aspect of Objective-C ;-) – Shiun Aug 23 '12 at 20:48
-
1@abellina no you can't currently mock class methods with OCMock – Christopher Pickslay Sep 27 '12 at 00:07
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.

Erik Doernenburg
- 2,933
- 18
- 21
-
-
Yes - this is just using KVC within the Foundation framework. See here: https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/KeyValueCoding/Articles/KeyValueCoding.html#//apple_ref/doc/uid/10000107-SW1 – Sean Michael Dorian Aug 17 '15 at 20:42