Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C - Unit Testing & Mocking Objects?

How do you unit test Objective C code? (iPhone)

In other languages such as java and .Net you can use Dependency Injection, to be able to unit test and pass mocked object in your current code. However, I could not find a reliable dependency injection framework for objective c.

Let's say you want to write a unit test for the code below, how can you mock MyObject?

- (void) methodToBeTested
{
     NSString str = @"myString";
     MyObject object = [[MyObject alloc] init];
     [object setString:str];
     [object doStuff];
     [object release];
}

This is how I would do it with dependency injection. Is there a similar way to achieve this on objective c?

@Inject MyObject object;

public void methodToBeTested()
{
     String str = "myString";
     // object is automatically instantiated (Dependency Injection)
     object.setString(str);
     object.doStuff();
}
like image 350
aryaxt Avatar asked Mar 29 '11 18:03

aryaxt


1 Answers

Inversion of control is still feasible in objective-c. You can certainly design your classes with constructor-based or property-based dependency injection in mind but I don't think you'll find an annotation based dependency injection framework like you are used to.

[[ClassToBeTested alloc] initWithDependency:foo andOtherDepedency:bar];

ClassToBeTested *objectUnderTest = [[ClassToBeTested alloc] init];
objectUnderTest.dependency = foo;
objectUnderTest.otherDependency = bar;

I've seen a couple of different approaches to building dependency injection frameworks for objective-c including https://github.com/mivasi/Objective-IOC but I can't comment on their maturity or usefulness.

For object mocking and stubbing look at OCMock.

like image 195
Jonah Avatar answered Oct 08 '22 17:10

Jonah