在被测代码中调用[MyManager sharedInstance]时,OCMock如何自动强制被测代码使用这个模拟实例?有人可以向我解释一下吗? 解决方案 partialMockForObject 模拟您传递给它的对象.在这种情况下,您正在模拟单例(共享)对象.你不必注入任何东西,因为 sharedInstance 总是返回相同的对象,现在被嘲笑.它仍然是相同的参考.将部分模拟想象成对传递对象的简单修改,它不会创建新实例,因此您不必在这种特定情况下注入它.I am new in OCMock.I use dispatch_once() created a singleton class MyManager :@implementation MyManager+ (id)sharedInstance { static MyManager *sharedMyManager = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ sharedMyManager = [[self alloc] init]; }); return sharedMyManager;}I have a method in School class which uses the above singleton:@implementation School...- (void) createLecture { MyManager *mgr = [MyManager sharedInstance]; [mgr checkLectures]; ...}@endNow, I want to unit test this method, I use a partial mock of MyManager:- (void) testCreateLecture { // create a partially mocked instance of MyManager id partialMockMgr = [OCMockObject partialMockForObject:[MyManager sharedInstance]]; // run method to test [schoolToTest createLecture]; ...}I noticed that with OCMock, after I created the partial mock of my singleton MyManager instance, when run my method under test, it automatically use the partially mocked instance.This is a bit weird to me, since in my test case above, I only created the partial mock of MyManager instance without injecting it to MyManager class,how does OCMock automatically force the code under test use this mocked instance when [MyManager sharedInstance] is called in the code under test ? Could someone explain to me this? 解决方案 partialMockForObject mocks the object you are passing to it.In this case you are mocking the singleton (shared) object. You don't have to inject anything because sharedInstance is always returning the same object, now mocked. It is still the same reference.Imagine partial mocking as a simple mutation of the passed object, it doesn't create a new instance so you don't have to inject it in this specific case. 这篇关于OCMock 在被测代码中自动使用模拟实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-12 01:28