强迫症 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];
强迫症3
// 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 功能中的类方法部分
备择方案
如果您想测试由于任何原因无法重构的遗留代码,这个(奇怪的)解决方案可能很有用。但是,如果您可以修改代码,则应该重构它并获取一个ExtClass
对象作为参数,而不是字符串,从而委派该ExtClass
方法的创建。您的生产和测试代码会更简单、更清晰,尤其是在更复杂的现实生活案例中,而不是在这个简单的示例中。