在IOSApp测试过程中,如果遇到异常情况,App通过Nslog输出相应的日志信息,而我们测试又需要对其进行验证的时候。
首先要将输出日志重定向,然后才能进行相应的处理和验证,具体代码如下所示:
1,将Nslog输出重新定位到文件
+(void)writeLogToFile{NSArray *paths =
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsPath
= [paths objectAtIndex:0];
NSString *loggingPath =
[documentsPath stringByAppendingPathComponent:@"/mylog.log"];
//删除原日志文件
NSFileManager *manager
= [NSFileManager defaultManager];
BOOL isExist = [manager
fileExistsAtPath:loggingPath];
if(isExist){
BOOL sucess4 = [manager
removeItemAtPath:loggingPath error:nil];
if(sucess4){
//删除成功
}else{
//删除失败
}
}
origin=dup(STDERR_FILENO);
freopen([loggingPath
cStringUsingEncoding:NSASCIIStringEncoding], "a+", stderr);
logfilepath=loggingPath;
}
2,检测日志中是否有相应该的文字
+(Boolean)CheckLogOutput:(NSString *)logcheck{
NSString
*loggingPath=logfilepath;
//读取文件
NSString *str1 =
[NSString stringWithContentsOfFile:loggingPath
encoding:NSUTF8StringEncoding error:nil];
//Boolean *chres=[str1
containsString:logcheck];
if ([str1
rangeOfString:logcheck].location==NSNotFound)
{
return false;
}
else
{
return true;
}
}
3,恢复日志重定向
+(void)redirectLogBack{dup2(origin,
STDERR_FILENO);
}