I want to write tests for a singleton class MySingleton
@interface MySingleton : NSObject
{
SomeClass* _someClass;
}
@property (class, readonly, strong) Class_B* shared;
@end
In the tests, I want to be able to substitute the concrete SomeClass with a fake one, so I defined a protocol that SomeClass should conform to:
@protocol SomeProtocol
@end
@interface SomeClass : NSObject <SomeProtocol>
@end
@interface MySingleton : NSObject
{
id<SomeProtocol> _someClass;
}
@property (class, readonly, strong)MySingleton* shared;
- (instancetype)initWithSomeClass:(id<SomeProtocol>)someClass;
@end
@implementation MySingleton
+ (MySingleton*)shared {
static MySingleton* mySingleton;
static dispatch_once_t predicate;
dispatch_once(&predicate, ^{
SomeClass* someClass = [[SomeClass alloc] init];
mySingleton = [[MySingleton alloc] initWithSomeClass:someClass];
});
return mySingleton;
}
- (instancetype)initWithSomeClass:(id<SomeProtocol>)someClass {
self = [super init];
if (self) {
_someClass = someClass;
}
return self;
}
@end
Now in my tests I define a fake class:
@interface someClassFake : NSObject <SomeProtocol>
@end
and initialising MySingleton with it:
SomeClassFake* someFakeClass = [[SomeClassFake alloc] init];
MySingletone* mySingleton = [[MySingleton alloc] initWithObject: someClassFake];
The only problem I left with is that in the test suit, although I'm not using the concrete SomeClass I am still dependent on it because it is being used in the shared getter and the linker will ask me to provide the implementation for it. What is the best design solution so that my test suit will not be dependent on SomeClass?
Aucun commentaire:
Enregistrer un commentaire