Search code examples
objective-cunit-testingmockingocmock

How can i unit test an object internal to a method in Objective-C?


I'm wondering how to go about testing this. I have a method that takes a parameter, and based on some properties of that parameter it creates another object and operates on it. The code looks something like this:

- (void) navigate:(NavContext *)context {
  Destination * dest = [[Destination alloc] initWithContext:context];
  if (context.isValid) {
    [dest doSomething];
  } else {
    // something else
  }
  [dest release];
}

What i want to verify is that if context.isValid is true, that doSomething is called on dest, but i don't know how to test that (or if that's even possible) using OCMock or any other traditional testing methods since that object is created entirely within the scope of the method. Am i going about this the wrong way?


Solution

  • You could use OCMock, but you'd have to modify the code to either take a Destination object or to use a singleton object which you could replace with your mock object first.

    The cleanest way to do this would probably be to implement a

    -(void) navigate:(NavContext *)context destination:(Destination *)dest;
    

    method. Change the implementation of -(void) navigate:(NavContext *)context to the following:

    - (void) navigate:(NavContext *)context {
        Destination * dest = [[Destination alloc] initWithContext:context];
        [self navigate:context destination:dest];
        [dest release];
    }
    

    This will allow your tests to call the method with an extra parameter directly. (In other languages, you would implement this simply by providing a default value for the destination parameter, but Objective-C does not support default parameters.)