gpt4 book ai didi

ios - 使用 OCMock 模拟 [[UIDevice currentDevice] userInterfaceIdiom]

转载 作者:行者123 更新时间:2023-12-01 17:42:03 24 4
gpt4 key购买 nike

我正在学习在单元测试中使用 OCMocks,并且我了解基础知识。但是,我不确定如何模拟对类方法的调用。

我想要:

[[UIDevice currentDevice] userInterfaceIdiom]

为我的测试用例返回不同(但有效)的接口(interface)习惯用法。
id mock = [OCMockObject mockForClass:[UIDevice class]];

// Would I use a mock or a stub to have UIDevice mock return
// currentDevice and then from it, return userInterfaceIdiom

最佳答案

模拟单例是很棘手的。你可以用一些运行时魔法来做到这一点。可以在 Matt Gallagher's invokeSupersequent macro 的帮助下完成.基本上,您将一个类别添加到您的测试用例中,该类别会覆盖 currentDevice。返回一个模拟,只有当你设置了模拟。这是设置:

#import "NSObject+SupersequentImplementation.h"

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-protocol-method-implementation"

@implementation UIDevice (UnitTests)

+(id)currentDevice {
if ([BaseTestCase mockDevice]) {
return [BaseTestCase mockDevice];
}

return invokeSupersequentNoArgs();
}

@end

#pragma clang diagnostic pop


static id mockDevice = nil;

+(id)mockDevice {
return mockDevice;
}

+(id)createMockDevice {
mockDevice = [OCMockObject mockForClass:[UIDevice class]];
return mockDevice;
}

+(id)createNiceMockDevice {
mockDevice = [OCMockObject niceMockForClass:[UIDevice class]];
return mockDevice;
}

-(void)tearDown {
mockDevice = nil;
[super tearDown];
}

然后,在您的测试中:
-(void)testShouldDoSomethingOnIpad {
id mockDevice = [BaseTestCase createNiceMockDevice];
[[[mockDevice stub] andReturnValue:OCMOCK_VALUE(UIUserInterfaceIdiomPad)] userInterfaceIdiom];

// do something iPad-specific

[mockDevice verify];
}

我做了一个 more detailed write-up of this approach一会儿回来。

关于ios - 使用 OCMock 模拟 [[UIDevice currentDevice] userInterfaceIdiom],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15954828/

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