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?

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 Answers2

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
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
  • Can you get properties like this as well? – fatuhoku Apr 03 '14 at 09:59
  • 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