Question

So, basically here's what I want to do. I'm testing a class and in order to do that I want to redefine "today" (or "now"), meaning that I can test date transitions and other related properties simply by stating, say, "tomorrow is now" and then write my asserts.

My idea is to put a custom Test category on NSDate (NSDate+Test). But, at this moment I'm no longer sure how and where that category will propagate. I mean, will my class-under-test (that uses NSDate) automatically start to use NSDate+Test?

Just to illustrate:

#include "MyClassUnderTest.h"
#include "NSDate+Test.h"

// Will MyClassUnderTest.h see and use NSDate+Test at all times?
Was it helpful?

Solution

The runtime will happily add the methods to NSDate, but the compiler will error out if you try to send a message that it hasn't seen declared.*

So as long as you import the header, your class will be able to use your new methods.

If you're talking about "overriding" a framework class's methods in a category, you should be aware that every use of that method in your process will use the new version. So if you clobber +[NSDate date], even Cocoa-internal calls to date will use your version.** This can easily result in weird, even dangerous behavior. You should prefer mocking to this kind of clobbering.

Also note that, because of this phenomenon, you should always prefix methods that you add to framework classes via categories.


*Under ARC, at least.

**Assuming that date was not originally itself implemented in a category; in that case, the results are "undefined behavior".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top