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:
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
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.
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.