最近抽空了解了一下objective-c上的一个比较好用的单体测试框架OCMock。(记得挺早的时候就看到过,不过一直没时间去仔细了解,这次就抽空试用了一下)
OCMock是在编写objective-c的单元测试能够在不影响其他关联代码的情况下为测试对象(类)提供预期的测试数据。对Java开发人员来说,这个类库其实与Java开发中的mockito是同一个用途的。
OCMock官网:http://ocmock.org/
下面举几个不同的数据注入方式。 #Settings
@interface Settings : NSObject
+(Settings *)sharedInstance;
@property(nonatomic, copy) NSString *email;
@end
@implementation Settings
//...省略
- (Settings *)init{
self = [super init];
if (self != nil) {
self.email = [ISRKeyChainUtil valueForKey:KEYCHAIN_EMAIL];
}
return self;
}
//...省略
@end
#ISRKeyChainUtil
@interface ISRKeyChainUtil : NSObject
/**
always return @"HelloWorld"
**/
+ (id)valueForKey:(NSString *)key;
@end
#UnitTest Code
- (void)testSharedInstance{
//[Settings sharedInstance] like java singleton class
id mockSettingsToTest = OCMPartialMock([Settings sharedInstance]);
OCMStub([mockSettingsToTest email]).andReturn(@"multiuser@multi.isr.co.jp");
Settings *settings = [Settings sharedInstance];
AssertStringEqual(settings.email,@"multiuser@multi.isr.co.jp");
[mockSettingsToTest stopMocking];
}
- (void)testDifferentInstance{
Settings *settingsWillMock = [[Settings alloc] init];
Settings *settingsNormal = [[Settings alloc] init];
id mockSettingsToTest = OCMPartialMock(settingsWillMock);
OCMStub([mockSettingsToTest email]).andReturn(@"multiuser@multi.isr.co.jp");
AssertStringEqual(settingsWillMock.email,@"multiuser@multi.isr.co.jp");
AssertStringEqual(settingsNormal.email,@"HelloWorld");
[mockSettingsToTest stopMocking];
}
- (void)testClassMock{
id mockISRKeyChainUtilToTest = OCMClassMock([ISRKeyChainUtil class]);
OCMStub(ClassMethod([mockISRKeyChainUtilToTest valueForKey:@"email"])).andReturn(@"multiuser@multi.isr.co.jp");
Settings *settings = [Settings sharedInstance];
AssertStringEqual(settings.email, @"multiuser@multi.isr.co.jp");
[mockISRKeyChainUtilToTest stopMocking];
}
//利用反射的方式来获取参数数据并传递指定的Return值回去
- (id)mockHttpClient {
U2FHttpClient *httpClient = [[U2FHttpClient alloc] init];
id mockU2FHttpClient = OCMPartialMock(httpClient);
ClientRegistrationRequest __block *clientRegistrationRequest = [MockDataUtil clientRegistrationRequest_Success];
OCMStub([mockU2FHttpClient retrieveRegistrationRequestWithClientIdentifierRequest:[OCMArg isKindOfClass:[ClientIdentifierRequest class]]])
.andDo(^(NSInvocation *invocation) {
__unsafe_unretained ClientIdentifierRequest *clientRequest;
[invocation getArgument:&clientRequest atIndex:2];
NSLog(@"1:%@",clientRequest);
NSLog(@"%@", clientRegistrationRequest);
[invocation setReturnValue:&clientRegistrationRequest];
});
return mockU2FHttpClient;
}