views:

13

answers:

1

Let's say I have a class DataFeed which creates an instance of another class, Parser, as part of its work. i.e.

Parser *parser = [[Parser alloc] init];
[parser start];

I'm writing unit tests for DataFeed. I want to substitute a mock for the Parser. I can't work out how best to do this. I'm sure I must be missing something really obvious.

I have considered the following approaches:

  1. using a reference to a Class: Class *myParser. I imagined that I could then do something like

    Class *myParser = [Parser class]; [myParser start];

    ...but from the docs (and trying it) it appears that you can't use Class pointers in this way

  2. Using a category to override alloc in the unit tests so that it returns a mock instead of an instance of the real class. However, the category applies to the entire unit test executable (unless I make multiple test targets for different sets of tests) which is a problem if I also want to test the parser class in the same executable. I could work around this by making the overriding alloc method return either mock or real depending on some setting. I think this method is viable (I haven't tried it), but it doesn't seem quite right somehow.

  3. Introducing a factory instance to create instances of Parser. i.e. instead of

    Parser *parser = [[Parser alloc] init]

    you might have

    Parser *parser = [self.parserFactory newParser];

    You could then inject a factory instance that creates mocks when doing testing.

I think this approach is also viable but I don't like it because the ParserFactory is additional complexity introduced just to allow mocking.

A: 

Maybe, you should try OCMock (http://www.mulle-kybernetik.com/software/OCMock/)?

kpower
OCMock will create a mock object for me. But the question is not how to create a mock but how to inject it into the class under test.
Urban Winter