Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 975
Shiun Avatar asked Aug 09 '12 23:08

Shiun


2 Answers

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
like image 67
Christopher Pickslay Avatar answered Oct 01 '22 15:10

Christopher Pickslay


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.

like image 42
Erik Doernenburg Avatar answered Oct 01 '22 14:10

Erik Doernenburg