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
대안
이 (이상한) 솔루션 섹션이 유용 할 수 있습니다 클래스 방법은 당신으로 인해 어떤 이유에 당신이 리팩토링 할 수없는 레거시 코드를 테스트 할 수 있습니다. 그러나 코드를 수정할 수있는 경우 리팩토링하고 ExtClass
개체를 매개 변수로 사용하여 문자열이 아닌 ExtClass
생성을 위임해야합니다. 제작 및 테스트 코드는이 단순한 예제가 아닌,보다 복잡한 실제 사례에서 더욱 간단하고 명확합니다.
메서드 반환 유형이 BOOL이고 문자열을 반환하고 있습니다. 그런 것들을 편집하고 바꿀 수 있습니까? 나는 문자열을 반환하고 싶지만 확실하지 않습니다. – e1985
감사합니다. 나는 그것을 고쳤다. – soguy