当从命令行运行 OCUnit 测试时,我无法弄清楚为什么钥匙串访问失败。
为了继续我的测试,我在我的单元测试目标中添加了一个 hacktastic 类别:
//
// SFHFKeychainUtils+UnitTestHacks.m
// CB30
//
// GRRR!!! http://stackoverflow.com/questions/9996578/ocunit-tests-fail-from-the-command-line-but-work-in-xcode-when-using-keychain-se
//
// Created by Joshua Vickery on 5/14/12.
//
#import "SFHFKeychainUtils+UnitTestHacks.h"
static NSMutableDictionary *fakeKeyChainHolder;
@implementation SFHFKeychainUtils (UnitTestHacks)
+ (NSMutableDictionary *)fakeKeyChainForServiceName:(NSString *)serviceName {
if (nil == fakeKeyChainHolder) {
fakeKeyChainHolder = [NSMutableDictionary dictionary];
}
NSMutableDictionary *fakeKeyChain = [fakeKeyChainHolder objectForKey:serviceName];
if (nil == fakeKeyChain) {
fakeKeyChain = [NSMutableDictionary dictionary];
[fakeKeyChainHolder setObject:fakeKeyChain forKey:serviceName];
}
return fakeKeyChain;
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-protocol-method-implementation"
+ (BOOL) deleteItemForUsername: (NSString *) username andServiceName: (NSString *) serviceName error: (NSError **) error
{
[[self fakeKeyChainForServiceName:serviceName] removeObjectForKey:username];
return YES;
}
+ (BOOL) storeUsername: (NSString *) username andPassword: (NSString *) password forServiceName: (NSString *) serviceName updateExisting: (BOOL) updateExisting error: (NSError **) error
{
[[self fakeKeyChainForServiceName:serviceName] setObject:password forKey:username];
return YES;
}
+ (NSString *) getPasswordForUsername: (NSString *) username andServiceName: (NSString *) serviceName error: (NSError **) error
{
return [[self fakeKeyChainForServiceName:serviceName] objectForKey:username];
}
#pragma clang diagnostic pop
@end
请注意,这不是一个好的解决方案,而是让单元测试工作直到找到更好的解决方案的变通方法。