我已经尝试了很多东西。这仍然不起作用:
id stringMock = OCMClassMock([NSString class]);
[[[[stringMock stub] ignoringNonObjectArgs] stringWithContentsOfURL:[OCMArg anyPointer] encoding:NSUTF8StringEncoding error:(NSError * __autoreleasing *)[OCMArg anyPointer]] andReturn:stringFromFile];
如何让 -[NSString stringWithContentsOfURL:encoding:error:] 在我的代码中的任何位置返回 stringFromFile
?
最佳答案
很遗憾,这是不可能的。
来自 OCMock documentation关于限制(第 10 节):
10.5 Class methods on NSString cannot be stubbed or verified
id stringMock = OCMClassMock([NSString class]); // the following will not work OCMStub([stringMock stringWithContentsOfFile:[OCMArg any] encoding:NSUTF8StringEncoding error:[OCMArg setTo:nil]]);
It is not possible to stub or verify class methods on NSString. Trying to do so has no effect.
但是,您可以包装 NSString
并模拟包装器。这意味着您需要用这个包装器替换代码中的所有调用,但测试会起作用..
这是一个例子:
包装器:
@interface NSStringWrapper : NSObject
+ (nullable id)stringWithContentsOfURL:(NSURL *)url;
@end
@implementation NSStringWrapper
+ (nullable id)stringWithContentsOfURL:(NSURL *)url
{
return [NSString stringWithContentsOfURL:url];
}
@end
测试:
static NSString *stringFromFile = @"myStringFromFile";
-(void)testStringWrapper
{
id nsstringWrapperMock = OCMClassMock([NSStringWrapper class]);
OCMStub(ClassMethod([nsstringWrapperMock stringWithContentsOfURL:OCMOCK_ANY])).andDo(^(NSInvocation *invocation)
{
[invocation setReturnValue:&stringFromFile];
});
NSURL *fakeURL = [NSURL URLWithString:@"htttp://google.com"];
NSString *test = [NSStringWrapper stringWithContentsOfURL:fakeURL];
XCTAssertEqual(test, stringFromFile, @"Should always return stringFromFile");
}
关于ios - OCMock:如何 stub -[NSString stringWithContentsOfURL:encoding:error:],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35143591/