我有一个模拟的DataLoader类,即使我自己调用该方法,我的期望也会失败:
- (voID)testSimpleMocking { // Mock the class ID mock = [OcmockObject niceMockForClass:[DataLoader class]]; // OverrIDe the 'dispatchLoadToAppDelegate:' to be a no-op [[[mock stub] andReturn:nil] dispatchLoadToAppDelegate:[OCMArg any]]; // Expect the method to be called [[mock expect] dispatchLoadToAppDelegate:[OCMArg any]]; // Call the method [mock dispatchLoadToAppDelegate:nil]; // Verify [mock verify];}
但是,当我运行此测试时,我收到错误:
/Users/Craig/projects/MyApp/UnkNown.m: -[MockingDataLoaderTest testSimpleMocking] : OcmockObject[DataLoader]:expected method was not invoked: dispatchLoadToAppDelegate:<OCMAnyConstraint: 0x1a3d890>
当我自己调用这个方法时,这怎么可能?
编辑:一个更复杂的案例:
- (voID)testDataLoaderWaitsForDownload { ID mock = [OcmockObject niceMockForClass:[DataLoader class]]; ID MetadataItem = [OcmockObject niceMockForClass:[NSMetadataItem class]]; // Prepare NSMetadataItem [[[MetadataItem expect] andReturn:nil] valueForAttribute:NSMetadataItemURLKey]; // CODERUN [mock waitForDownload:MetadataItem thenLoad:YES]; //VERIFY [MetadataItem verify];}
并执行waitForDownload:thenLoad:方法:
- (voID)waitForDownload:(NSMetadataItem *)file thenLoad:(BOol)load { NSURL *MetadataItemURL = [file valueForAttribute:NSMetadataItemURLKey]; ...
失败并出现错误:
UnkNown.m:0: error: -[MockingDataLoaderTest testDataLoaderWaitsForDownload] : OcmockObject[NSMetadataItem]: expected method was not invoked: valueForAttribute:@"kMDItemURL"解决方法 在您的测试中,存根优先,因为它首先被调用.如果您切换预期和存根的顺序,您的测试应该通过.
你同时使用expect和stub(具有相同的参数期望)的原因是确保至少发生一次调用,然后在没有失败的情况下响应后续调用.
如果你真的只想要一个方法调用,只需将andReturn:添加到expect子句中……
- (voID)test_dispatchLoadToAppDelegate_isCalledExactlyOnce { // Mock the class ID mock = [OcmockObject niceMockForClass:[DataLoader class]]; // Expect the method to be called [[[mock expect] andReturn:nil] dispatchLoadToAppDelegate:[OCMArg any]]; // Call the method [mock dispatchLoadToAppDelegate:nil]; // Verify [mock verify];}
另一种情况:
- (voID)test_dispatchLoadToAppDelegate_isCalledAtLeastOnce { // Mock the class ID mock = [OcmockObject niceMockForClass:[DataLoader class]]; // Expect the method to be called [[[mock expect] andReturn:nil] dispatchLoadToAppDelegate:[OCMArg any]]; // Handle subsequent calls [[[mock stub] andReturn:nil] dispatchLoadToAppDelegate:[OCMArg any]]; // Call the method [mock dispatchLoadToAppDelegate:nil]; // Call the method (again for fun!) [mock dispatchLoadToAppDelegate:nil]; // Verify [mock verify];}
对于这种特殊情况,看起来你可以使用niceMockForClass但是如果你想要存根返回非零,那么你必须以任何方式调用存根.
@H_502_68@ 总结以上是内存溢出为你收集整理的ios – OCMock“预期的方法没有被调用”,即使我自己称之为全部内容,希望文章能够帮你解决ios – OCMock“预期的方法没有被调用”,即使我自己称之为所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)