Varun Mehta
Varun Mehta

Reputation: 1753

How to Mock local variable without using OCMock

I'm writing test cases using XCTest framework provided by apple. I come up with situation where i want to mock local variables allocated inside the function like this below

-(void)myFunction{
   A* a = [[A alloc] init];
}

from my testcase class i want to mock class A inside my function testMyFunction . Is there any way to do it without using OCMock.

Upvotes: 1

Views: 412

Answers (2)

Jon Reid
Jon Reid

Reputation: 20980

If it's okay to create the instance first, then inject it using normal Dependency Injection techniques.

But if you need to ensure that the instance won't be created until it's needed, you have a few choices:

  • Inject a class, as @dasdom says. Then call its initializer when you need it.
  • Inject a block that acts as a Factory. Call it when you need it.
  • For more complex initialization: inject a Factory. I'd typically make this conform to a protocol, to make replacements clear.

Upvotes: 1

dasdom
dasdom

Reputation: 14063

You could inject the class to be used in the method into the system unter test. In the test you can use a different class.

Upvotes: 0

Related Questions