依赖注入测试类

时间:2018-07-19 09:25:10

标签: objective-c unit-testing testing dependency-injection dependencies

我想为单例类MySingleton编写测试

MySingletone.h:

@interface MySingleton : NSObject

@property (class, readonly, strong) Class_B* shared;

@end

MySingleton.m:

@interface MySingleton()
{
    SomeClass* _someClass;
}

@end

@implementation MySingletone

+ (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:(SomeClass*)someClass {
    self = [super init];
    if (self) {
        _someClass = someClass;
    }
    return self;
}

@end

在测试中,我希望能够用伪造的SomeClass代替具体的SomeClass,因此我定义了@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 应该符合的协议:

@interface someClassFake : NSObject <SomeProtocol>
@end

现在在我的测试中,我定义了一个假类:

MySingleton

并使用它初始化SomeClassFake* someFakeClass = [[SomeClassFake alloc] init]; MySingletone* mySingleton = [[MySingleton alloc] initWithObject: someClassFake];

SomeClass

我剩下的唯一问题是在测试服中,尽管我没有使用具体的shared,但我仍然依赖它,因为它正在SomeClass的getter和链接器将要求我为其提供实现。最好的设计解决方案是什么,以使我的测试服不依赖于align = 'c'

1 个答案:

答案 0 :(得分:0)

我想出的最佳解决方案是将$json_data = json_decode($return); $data = (array) $json_data->data; 吸气剂移至一个类别:

MySingletone + Shared.h:

shared

MySMySingletone + Shared.m:

@interface MySingleton (Shared)
@property (class, readonly, strong)MySingleton* shared;
@end

现在,在真实代码中,导入 MySingletone + Shared.h 而不是 MySingletone.h