2016-05-30 14 views
0

私はを使用して、iOSプロジェクトで単体テストを作成しています。テストケースでスタブ機能が動作していません

私はSchoolクラスの下foo方法があります。

@implementation School 
-(NSString *)foo: 
{ 
    // I need to mock this MyService instance in my test 
    MyService *service = [[MyService alloc] init]; 

    // I need to stub the function return for [service getStudent] 
    Student *student = [service getStudent]; 
    if (student.age == 12) { 
     //log the age is 12 
    } else { 
     //log the age is not 12 
    } 
    ... 
} 

Studentは次のようになります。私のテストケースで

@interface Student : NSObject 
@property NSInteger age; 
... 
@end 

、私はStudentを返すようにメソッド呼び出し[service getStudent]をスタブしたいの例:age値12

// use mocked service 
id mockService = OCMClassMock([MyService class]); 
OCMStub([[mockService alloc] init]).andReturn(mockService); 

// create a student instance (with age=12) which I want to return by function '-(Student*) getStudent:' 
Student *myStudent = [[Student alloc] init]; 
myStudent.age = 12; 

// stub function to return 'myStudent' 
OCMStub([mockService getStudent]).andReturn(myStudent); 

// execute foo method 
id schoolToTest = [OCMockObject partialMockForObject:[[School alloc] init]]; 
[schoolToTest foo]; 

テストケースを実行すると、student-(Student*)getStudent:メソッドで返されますが、12歳ではありません。なぜですか?

===== UPDATEは====

私は、インターネットに気づいた、誰かがスタブにallocinitを分離することが示唆されました。私はこの&は私のテストケース、-(Student*)getStudent:方法呼び出されるの実際の実装を実行します...私は理由を理解することはできませんないとき

// use mocked service 
id mockService = OCMClassMock([MyService class]); 
OCMStub([mockService alloc]).andReturn(mockService); 
OCMStub([mockService init]).andReturn(mockService); 
// stub function to return 'myStudent' 
OCMStub([mockService getStudent]).andReturn(myStudent); 

:私もそれをしようとしたが、それが言うように、それは動作しません。人々はそれが動作すると言います。

+1

[この回答](http://stackoverflow.com/a/18512663/765298)に示されているように、これを動作させるには 'alloc'と' init'メソッドを別にモックする必要があります。 'School'オブジェクトがあなたの' MyService'をパラメータとして取るように、あなたのコードを再設計することを強くお勧めします。これにより、テストとメンテナンスがより簡単になります。私はあなたの質問に重複していると言います。 – Losiowaty

+0

@Losiowaty、私は 'alloc'と' init'を別々にしようとしましたが、実際の実装を終了します。 –

+0

@Losiowaty、更新情報をご覧ください。そして私は本当に人々がなぜそれが働いていると言っているのか、私のために働いていないのかを知りたい –

答えて

0

initメソッドをモックすることはできません。これはドキュメント(Section 9.3)に記載されていますが、あまりにも隠されている可能性があります。

関連する問題