gpt4 book ai didi

ios - OCMockObject 模拟一个实例方法

转载 作者:行者123 更新时间:2023-11-29 12:49:47 30 4
gpt4 key购买 nike

我是 OCMockObjects 的新手,正在尝试模拟 ACAccount 类的实例方法:

-(NSArray *)accountsWithAccountType:(ACAccountType *)accountType;

我在测试类中写了这段代码来初始化mockObject:

ACAccountStore *accountStore = [[ACAccountStore alloc] init];
id mockAccountStore = [OCMockObject partialMockForObject:accountStore];
[[[mockAccountStore stub] andReturn:@[@"someArray"]] accountsWithAccountType:[OCMArg any]];

//call the test method
[myClassInstance methodToTest];

在 myClass 中,方法 ToTest 如下所示:

 -(void) methodToTest
{
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
ACAccountType* accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
NSArray* expectedArray = [accountStore accountsWithAccountType:accountType];
//Getting nil value to Array rather than the returned value in stub
}

知道我在这里做错了什么吗?谢谢。

最佳答案

Ben Flynn 是正确的,您需要一种方法将 AccountStore 注入(inject)到您正在测试的对象中。执行此操作的另外两种方法:

1) 使 accountStore 成为在初始化时设置的被测类的属性,然后在您的测试中使用模拟覆盖该属性。

2) 创建一个类似于 -(ACAccountStore *)accountStore 的方法来初始化帐户存储,但在您的测试中模拟该方法:

ACAccountStore *accountStore = [[ACAccountStore alloc] init];
id mockAccountStore = [OCMockObject partialMockForObject:accountStore];
[[[mockAccountStore stub] andReturn:@[@"someArray"]] accountsWithAccountType:[OCMArg any]];

id mockInstance = [OCMockObject partialMockForObject:myClassInstance];
[[[mockInstance stub] andReturn:mockAccountStore] accountStore];

// call the test method
[myClassInstance methodToTest];

关于ios - OCMockObject 模拟一个实例方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22688353/

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