2014-03-27 53 views
1

我是新來OCMockObjects並試圖嘲弄ACAccount類的實例方法:OCMockObject嘲諷的實例方法

-(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 methodToTest看起來像這樣:

-(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 
} 

任何想法我在這裏做錯了什麼。謝謝。

回答

0

您正在創建一個模擬,但您正在測試的方法不是使用模擬,而是使用原始ACAccountStore類的一個實例。

如果您願意,使methodToTest可測試的最簡單方法是讓它接受一個ACAccountStore實例作爲參數。

- (void)methodToTestWithAccountStore:(ACAccountStore *)accountStore; 

然後你的測試看起來是這樣的:

[myClassInstance methodToTest:mockAccountStore]; 

這將遵循依賴注入模式。如果你不喜歡這種模式,你可以 ACAccountStore的模擬的alloc方法來回報您的模擬對象,但我始終警惕可能產生的副作用,從嘲諷alloc,而是建議對ACAccountStore創建一個工廠:

@interface ACAccountStore (Factory) 
+ (instancetype)accountStore; 
@end 
@implementation ACAccountStore 
+ (instancetype)accountStore { return [[ACAccountStore alloc] init]; } 
@end 

如果你使用這種模式,你可以模擬你的工廠方法。

1

Ben Flynn是正確的,您需要一種方法將AccountStore注入到您正在測試的對象中。其他兩種方法:

1)將accountStore設爲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]; 
+0

我喜歡這個主意,但它確實意味着你正在擴大範圍的ACAccountStore對象。雖然不是很大的交易。 –

+0

是的,我認爲第二種方法基本上等同於OP的原始代碼 - 它只是將初始化移動到您可以在測試時攔截的方法。 –