Tracer
Tracer 是一个实验性的测试工具,允许您记录并回放 Objective-C 中任意对象的行为。
假设您在代码中有一个依赖项,ThatThing
。您调用 ThatThing
,它又调用您,行为根据用户输入或环境因素而变化。
@protocol ThatInterface <NSObject>
- (void)someCommand:(int)i;
- (void)someOtherCommand:(NSArray *)objects;
// ...
- (void)onError:(NSError *)error;
- (void)onOtherError:(NSError *)error;
@end
@interface ThatThing : NSObject <ThatInterface>
@end
测试复杂异步行为很困难,尤其是当您不控制行为源时。
Tracer 允许您将 ThatThing
的行为作为跟踪来记录
ThatThing *thing = [ThatThing new];
TRCRecorder *recorder = [TRCRecorder new];
[recorder startRecording:thing protocol:@protocol(ThatInterface)];
NSString *result = [thing someCommand:-100];
[recorder stopRecording:thing protocol:@protocol(ThatInterface) completion:^(TRCTrace *trace, NSError *error) {
// save trace
}];
记录完成后,Tracer 将跟踪输出到控制台作为 JSON,因此您可以 将行为保存到文件。
2019-04-17 23:01:22.689124-0700 xctest[62038:4377601] -----BEGIN TRACE JSON-----
{
"start_ms" : 1551678464427,
"id" : "trace",
"protocol" : "SomeProtocol",
"calls" : [
{
"id" : "call",
"start_ms" : 203,
"method" : "someCommand:",
"arguments" : [
{
"id" : "value",
"type" : "int",
"object_type" : "not_an_object",
"object_value" : -100
}
],
"return_value" : {
"id" : "value",
"type" : "void",
}
}
]
}
-----END TRACE JSON-----
在您的测试中,而不是模拟 ThatThing
的复杂行为,您只需简单地 播放记录的行为。
ThatThing *thing = [ThatThing new];
TRCTrace *trace = [TRCTrace loadFromJSONFile:@"saved_trace"];
[TRCPlayer playTrace:trace onTarget:thing completion:^(NSError * _Nullable error) {
}];