OCMock 2
id mock = [OCMockObject mockForClass:[ExtClass class]];
// We stub someMethod
BOOL returnedValue = YES;
[[[mock stub] andReturnValue:OCMOCK_VALUE(returnedValue)] someMethod];
// Here we stub the alloc class method **
[[[mock stub] andReturn:mock] alloc];
// And we stub initWithParam: passing the param we will pass to the method to test
NSString *param = @"someParam";
[[[mock stub] andReturn:mock] initWithParam:param];
// Here we call the method to test and we would do an assertion of its returned value...
[YourClassToTest foo:param];
OCMock3
// Parameter
NSURL *url = [NSURL URLWithString:@"http://testURL.com"];
// Set up the class to mock `alloc` and `init...`
id mockController = OCMClassMock([WebAuthViewController class]);
OCMStub([mockController alloc]).andReturn(mockController);
OCMStub([mockController initWithAuthenticationToken:OCMOCK_ANY authConfig:OCMOCK_ANY]).andReturn(mockController);
// Expect the method that needs to be called correctly
OCMExpect([mockController handleAuthResponseWithURL:url]);
// Call the method which does the work
[self.myClassInstance authStarted];
OCMVerifyAll(mockController);
नोट्स
सुनिश्चित करें कि दोनों ही मामलों में आप दो विधियों (alloc
और init...
विधि) ठूंठ। साथ ही, सुनिश्चित करें कि दोनों स्टबिंग कॉल क्लास मॉक के इंस्टेंस पर (कक्षा स्वयं नहीं) पर बनाई गई हैं।
डॉक्स: कक्षा तरीकों मामले में OCMock features
वैकल्पिक
यह (अजीब) समाधान में अनुभाग उपयोगी हो सकता है आप विरासत कोड है कि जो भी कारण की वजह से आप refactor नहीं कर सकते हैं परीक्षण करना चाहते हैं। हालांकि, अगर आप कोड को संशोधित कर सकते हैं तो आपको इसे दोबारा प्रतिक्रिया देना चाहिए और ExtClass
ऑब्जेक्ट को एक पैरामीटर के रूप में प्राप्त करना चाहिए, स्ट्रिंग नहीं, उस विधि से ExtClass
के निर्माण को दर्शाता है। आपका उत्पादन और परीक्षण कोड सरल और स्पष्ट होगा, खासकर एक जटिल वास्तविक जीवन मामले में, इस सरल उदाहरण में नहीं।
आपकी विधि वापसी प्रकार BOOL है और फिर आप एक स्ट्रिंग लौट रहे हैं। क्या आप इनमें से किसी भी चीज को संपादित और बदल सकते हैं? मुझे लगता है कि आप एक स्ट्रिंग वापस करना चाहते हैं, लेकिन मुझे यकीन नहीं है। – e1985
धन्यवाद। मैंने इसे ठीक कर दिया है। – soguy