gpt4 book ai didi

objective-c - OCMock 期待一个类方法

转载 作者:搜寻专家 更新时间:2023-10-30 20:05:49 27 4
gpt4 key购买 nike

所以我希望能够为我的一个类调用一个类方法

@implementation CustomClass

+ (void)method:(NSString*)string{
[[self class] method:string object:nil];

}

+ (void)method:(NSString *)string object:(id)object {
//do something with string and object
}

@end

我想调用 [CustomClass method:@""] 并期待 method: string:

我尝试过 method swizzling,但它似乎只对 stub 有用。

最佳答案

您可以使用 method swizzling 或 OCMock 进行测试。

通过方法调配,首先我们在您的测试实现文件中声明以下变量:

static NSString *passedString;
static id passedObject;

然后我们实现一个 stub 方法(在测试类中)并进行调配:

+ (void)stub_method:(NSString *)string object:(id)object
{
passedString = string;
passedObject = object;
}

- (void) test__with_method_swizzling
{
// Test preparation
passedString = nil;
passedObject = [NSNull null];// Whatever object to verify that we pass nil

Method originalMethod =
class_getClassMethod([CustomClass class], @selector(method:object:));
Method stubMethod =
class_getClassMethod([self class], @selector(stub_method:object:));

method_exchangeImplementations(originalMethod, stubMethod);

NSString * const kFakeString = @"fake string";

// Method to test
[CustomClass method:kFakeString];

// Verifications
STAssertEquals(passedString, kFakeString, nil);
STAssertNil(passedObject, nil);

method_exchangeImplementations(stubMethod, originalMethod);
}

但是我们可以使用 OCMock 以更简单的方式完成同样的事情:

- (void) test__with_OCMock
{
// Test preparation
id mock = [OCMockObject mockForClass:[CustomClass class]];

NSString * const kFakeString = @"fake string";
[[mock expect] method:kFakeString object:nil];

// Method to test
[CustomClass method:kFakeString];

// Verifications
[mock verify];
}

关于objective-c - OCMock 期待一个类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19386817/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com