OCMock 3 參考

1.Creating mock objects

1.1Class mocks


idclassMock=OCMClassMock([SomeClassclass]);


1.2Protocol mocks


idprotocolMock=OCMProtocolMock(@protocol(SomeProtocol));


Creates a mock object that can be used as if it were an instance of an object that implementsSomeProtocol. Otherwise they work like class mocks.

創(chuàng)建一個mock對象,如果它是一個實例對像實現(xiàn)的SomeProtocol能使用他,否側這個工作像classmock

1.3Strict class and protocol mocks


idclassMock=OCMStrictClassMock([SomeClassclass]);

idprotocolMock=OCMStrictProtocolMock(@protocol(SomeProtocol));


創(chuàng)建一個嚴格的mock對象模式。默認情況下mock很好,他們返回nil(或正確的返回類型默認值)的方法被調用。相比之下,嚴格Mock引發(fā)一個異常當他們收到的方法沒有明確的預期。請參閱下面的嚴格模擬和期望。

1.4 Partial mocks(部分 mocks)

idpartialMock=OCMPartialMock(anObject);

Creates a mock object that can be used in the same way asanObject. Any method that is not stubbed is forwarded toanObject. When a method is stubbed and that method is invoked using a reference to the real object, the mock will still be able to handle the invocation. Similarly, when a method is invoked using a reference toanObject, rather than the mock, it can still be verified later.

譯:創(chuàng)建一個mock對象,可用于asanObject一樣。不是的是轉發(fā)toanObject的任何方法。當一個方法的調用,方法使用對真實對象的引用,mock仍然能夠處理調用。同樣,當調用一個方法使用toanObject的引用,而不是mock,它仍然可以得到證實。

There are some subtleties when using partial mocks. Seepartial mocksbelow.

1.5 Observer mocks(觀察 mocks)

idobserverMock=OCMObserverMock();

Creates a mock object that can be used to observe notifications. The mock must be registered in order to receive notifications. Seeobserver mocksbelow for details.

譯:創(chuàng)建一個mock對象,可以用來觀察通知。mock必須注冊以接收通知。Seeobserver mocksbelow詳情。

2 Stubbing methods(stub方法)

2.1 Stubbing methods that return objects(stub方法返回對象)

OCMStub([mocksomeMethod]).andReturn(anObject);

Tells the mock object that whensomeMethodis called it should returnanObject.

譯:講述了mock對象,當someMethod 呼叫它應該返回一個對象。

2.2 Stubbing methods that return values(stub返回值的方法)

OCMStub([mockaMethodReturningABoolean]).andReturn(YES);

For methods that return primitive values it is important to use the right type of value. If, for example, a method returns alongbut the stub uses anintan error will occur. The message will include the expected and the actual type (using Objective-C type codes such as “q” forlongand “i” forint).

譯:返回原始值的方法是很重要的使用正確的類型的值。例如,如果一個方法返回alongbut stub使用anintan就會發(fā)生錯誤。消息將包括預期的和實際的類型(使用objective - c類型代碼如“q”forlongand“我”)。

2.3 Delegating to another method(委托給另一個方法)

OCMStub([mocksomeMethod]).andCall(anotherObject,@selector(aDifferentMethod));

In this case the mock object will callaDifferentMethodonanotherObjectwhensomeMethodis called. The signature of the replacement method must be the same as that of the method that is replaced. Arguments will be passed, and the return value of the replacement method is returned from the stubbed method. It is common to implement the replacement method in the test case itself.

譯:在這種情況下,將callaDifferentMethodonanotherObjectwhensomeMethodis調用mock對象。替代方法的簽名必須與被替換的方法。參數將傳遞和返回值返回的替代方法的方法。通常實現(xiàn)替代方法在測試用例本身。

2.4 Delegating to a block(委托給 塊)

OCMStub([mocksomeMethod]).andDo(^(NSInvocation*invocation){/* block that handles the method invocation */});

The mock object will call the passed block whensomeMethodis called. The block can read the arguments from the invocation object, and it can use the invocation object to set up a possible return value.

譯:mock對象將調用通過阻止someMethodis打電話時。塊可以讀取的參數調用對象,它可以使用調用對象建立一個可能的返回值

2.5 Returning values in pass-by-reference arguments(返回值引用傳遞參數)

OCMStub([mocksomeMethodWithReferenceArgument:[OCMArgsetTo:anObject]]);

OCMStub([mocksomeMethodWithReferenceArgument:[OCMArgsetToValue:OCMOCK_VALUE((int){aValue})]]);

The mock object will set the reference that is passed to the method toanObjectandaValue. UsesetTo:for pass-by-reference arguments that return objects andsetToValue:andOCMOCK_VALUE()for arguments that return primitives.

譯:mock對象將toanObjectandaValue的引用傳遞給方法。UsesetTo:andsetToValue引用傳遞參數,返回對象:andOCMOCK_VALUE()的參數返回原語。

2.6 Invoking block arguments(調用塊參數)

OCMStub([mocksomeMethodWithBlock:[OCMArginvokeBlock]]);

OCMStub([mocksomeMethodWithBlock:([OCMArginvokeBlockWithArgs:@"First arg",nil])]);

The mock object will invoke the block passed as an argument to the stubbed method. If the block takes arguments andinvokeBlockis used, the default values for the argument types are used, e.g. zero for a numerical type. UsinginvokeBlockWithArgs:it is possible to specify which arguments to invoke the block with; non-object arguments must be wrapped in value objects and the expression must be wrapped in round brackets.

譯:mock對象將調用塊作為參數傳遞的方法。andinvokeBlockis如果塊參數使用默認值的參數類型,如零數值類型。UsinginvokeBlockWithArgs:可以指定哪個參數來調用塊;非參數必須用值對象和表達式必須用圓括號。

2.7 Throwing exceptions(拋出異常)

OCMStub([mocksomeMethod]).andThrow(anException);

WhensomeMethodis invoked the stub will throwanException.

譯:當someMethodis調用stub將throwanException。

2.8 Posting notifications(發(fā)布通知)

OCMStub([mocksomeMethod]).andPost(aNotification);

When someMethodis invoked the stub will postaNotification.

譯:當someMethodis調用stub將發(fā)布通知。

2.9 Chaining stub actions(鏈接stub的行為)

OCMStub([mocksomeMethod]).andPost(aNotification).andReturn(aValue);

All actions such asandReturnandandPostcan be chained. In this example the mock object will post a notification and return the value.

譯:所有操作這樣的asandReturnandandPostcan是鏈接。在這個例子中mock對象將發(fā)布一個通知和返回的值。

2.10 Forwarding to the real object / class(轉發(fā)到真正的對象/類)

OCMStub([mocksomeMethod]).andForwardToRealObject();

When using a partial mock and when mocking class methods it is possible to stub a method and forward it to the real object (in case of partial mocks) or to the class (when mocking class methods). This is only useful when chaining actions or when usingexpectations.

2.11 Doing nothing

?OCMStub([mocksomeMethod]).andDo(nil);

It is possible to passnilinstead of a block toandDo. This is only useful with partial mocks or when mocking class methods. In these cases usingandDo(nil)effectively suppresses the behaviour in the existing class.

譯:當使用部分mock當mock類方法可以存根方法并將其轉發(fā)給實際對象(在部分mock的情況下)或類(當mock類方法)。這只是有用或者當usingexpectations鏈接操作

3 Verifying interactions(驗證相互作用)

3.1 Verify-after-running(驗證-前-運行)

idmock=OCMClassMock([SomeClassclass]);/* run code under test */OCMVerify([mocksomeMethod]);

Verifies thatsomeMethodhas been called by the code under test. If the method has not been invoked an error is reported. In Xcode and AppCode the error is reported on the line of the verify, for other test environments an exception is thrown.

譯:驗證thatsomeMethodhas被測試的代碼。如果沒有被調用的方法一個錯誤報告。在Xcode和本地錯誤報告的驗證,為其他測試環(huán)境就會拋出一個異常。

It is possible to useargument constraintsin the verify statement.

3.2 Stubs and verification(stub和驗證)

idmock=OCMClassMock([SomeClassclass]);

OCMStub([mocksomeMethod]).andReturn(myValue);

/* run code under test */

OCMVerify([mocksomeMethod]);

It is possible to stub a method and still verify that it has been called.

譯:它仍然被稱為存根方法和驗證

4 Argument constraints(參數約束)

4.1 The any constraint(任何約束)

OCMStub([mocksomeMethodWithAnArgument:[OCMArgany]])OCMStub([mocksomeMethodWithPointerArgument:[OCMArganyPointer]])OCMStub([mocksomeMethodWithSelectorArgument:[OCMArganySelector]])

Adds a stub for the methods which is active for all invocations, no matter what argument is passed. Pointers and selectors require special treatment as shown above. Arguments that are neither objects nor pointers or selectors cannot be ignored using ananyplaceholder (for details see thisforum thread). See just below for a workaround.

4.2 Ignoring non-object arguments(忽略非參數)

[[[mockstub]ignoringNonObjectArgs]someMethodWithIntArgument:0]

This tells the mock to ignore all non-object arguments in the invocation. It will accept any invocation ofsomeMethodWithIntArgument:no matter what argument is actually passed. If the method has object arguments as well as non-object arguments, the object arguments can still be constrained as usual using the methods onOCMArg.

譯:這告訴mock忽略所有非參數的調用。它將接受任何調用someMethodWithIntArgument:無論什么觀點實際上是通過。如果參數和非參數方法對象,對象參數仍然可以限制像往常一樣OCMArg上使用的方法

NOTE:this should have a modern syntax.

4.3 Matching arguments(匹配的參數)

OCMStub([mocksomeMethod:aValue)OCMStub([mocksomeMethod:[OCMArgisNil]])OCMStub([mocksomeMethod:[OCMArgisNotNil]])OCMStub([mocksomeMethod:[OCMArgisNotEqual:aValue]])OCMStub([mocksomeMethod:[OCMArgisKindOfClass:[SomeClassclass]]])OCMStub([mocksomeMethod:[OCMArgcheckWithSelector:aSelectoronObject:anObject]])OCMStub([mocksomeMethod:[OCMArgcheckWithBlock:^BOOL(idvalue){/* return YES if value is ok */}]])

If an argument is passed when the stub is created, the stub only matches invocations with that exact argument. Calls with different arguments are not matched. TheOCMArgclass provides several methods that allow matching values in different ways.

譯:如果一個參數是通過創(chuàng)建存根時,存根只匹配調用以同樣的論點。調用不同的參數不匹配。OCMArg類提供了一些方法,允許以不同的方式匹配的值

ForcheckWithSelector:onObject:, when the mock object receivessomeMethod:, it invokesaSelectoronanObject. If the method takes an argument the mock will pass the argument that was passed tosomeMethod:. The method should return a boolean indicating whether the argument matched the expectation or not.

譯:checkWithSelector:onObject:,當模擬對象接收到someMethod:,它調用aSelector anObject。如果方法接受一個參數的模擬將參數傳遞給someMethod:。方法應該返回一個布爾值表示是否參數匹配的期望。

4.4 Using Hamcrest matchers(使用Hamcrest匹配器)

OCMStub([mocksomeMethod:startsWith(@"foo")])

It is also possible to useHamcrest matchers. This will only work when the Hamcrest framework is explicitly linked by the unit test bundle. OCMock does not declare a dependency on Hamcrest and discovers it using runtime functions.

譯:還可以使用Hamcrest匹配器。這只會工作Hamcrest框架明確相關的單元測試包。OCMock不聲明一個依賴Hamcrest和發(fā)現(xiàn)它使用運行時功能。

5Mocking class methods

5.1 Stubbing class methods(stub類方法)

idclassMock=OCMClassMock([SomeClassclass]);

OCMStub([classMockaClassMethod]).andReturn(@"Test string");

// result is @"Test string"

NSString*result=[SomeClassaClassMethod];

Stubs for class methods are set up exactly like stubs for instance methods. However, behind the scenes the mock object makes some changes to the class. (It dynamically creates a new meta class and makes the class use that instead of its own meta class.) This allows OCMock to stub calls which are made directly to the class.

譯:存根類方法建立的存根實例方法完全一樣。然而,在幕后模擬對象使得類的一些變化。(它動態(tài)地創(chuàng)建一個新的元類,使類使用,而不是自己的元類)。這允許OCMock存根調用直接到類。

IMPORTANT:If the mock object that added a stubbed class method is not deallocated then the stubbed method will persist across tests. If multiple mock objects manipulate the same class at the same time the behaviour is undefined.

譯:重要:如果模擬對象添加了一個sub類方法不一致的方法,測試會持續(xù)。如果多個模擬對象同時操作同一個類的行為是未定義的

5.2 Verifying invocations of class methods(驗證類方法的調用)

idclassMock=OCMClassMock([SomeClassclass]);

/* run code under test */

OCMVerify([classMocka ClassMethod]);

Verification is done in the same way as with instance methods. As described above, calls can be made directly to the class.

譯:實例驗證后以同樣的方式與方法。如上所述,可以直接調用類。

5.3 Disambiguating class and instance methods(二義性消除類和實例方法)

idclassMock=OCMClassMock([SomeClassclass]);

OCMStub(ClassMethod([classMockambiguousMethod])).andReturn(@"Test string");

// result is @"Test string"

NSString*result=[SomeClassam biguousMethod];

In cases where a class method should be stubbed but the class also has an instance method with the same name as the class method, as assumed withambiguousMethodabove, the intent to mock the class method must be made explicit usingClassMethod().

譯:在這種情況下,一個sub類方法,但具有相同名稱的類也有一個實例方法的類方法,假定withambiguousMethodabove,意圖模擬類方法必須明確usingClassMethod()。

5.4 Restoring the class(恢復類)

idclassMock=OCMClassMock([SomeClassclass]);

/* do stuff */

[classMock stopMocking];

The class can be returned to its original state by callingstopMocking. This is only necessary if the original state must be restored before the end of the test. The? mock automatically callsstopMockingduring its own deallocation.

譯:他類可以通過調用stopMocking回到初始狀態(tài)。這僅僅是必要的,如果必須在恢復前結束測試。mocK自動調用stopMocking期間自己的回收。

When the class is returned to its original state, its meta class will be switched back to the original meta class. This effectively removes all the stubs. However, this also makes it impossible for the mock to add new stubs or to verify interactions. You should really not use a mock after having calledstopMocking.

譯:當這個類回到原來的狀態(tài),它的元類將切換回原來的元類。這將有效消除所有的subs。然而,這也使得模擬無法添加新存根或驗證交互。你不應該使用一個模擬稱為stopMocking后

6 Partial mocks(部分 mocks)

6.1 Stubbing methods(sub方法)

idpartialMock=OCMPartialMock(anObject);

OCMStub([partialMocksomeMethod]).andReturn(@"Test string");

// result1 is @"Test string"

NSString*result1=[partialMocksomeMethod];

// result2 is @"Test string", too!

NSString*result2=[anObjectsomeMethod];

From an API perspective stubs on partial mocks are set up in the same way as on class and protocol mocks. Partial mocks alter the class of the mocked object, though. (In fact, they create a subclass and switch the class of the mocked object to that subclass.) This means that calls using a reference to the real object, even includingselfin methods where the object calls itself, are also affected by stubs and expectations.

譯:從一個API的角度來看subs上部分mock設置相同的方式mock類和協(xié)議。部分mock改變類 的對象,。(事實上,他們創(chuàng)建一個子類和開關類子類的對象。)這意味著調用使用對真實對象的引用,甚至包括自我在對象調用方法本身,也受到stubs和期望。

6.2 Verifying invocations(驗證調用)

idpartialMock=OCMPartialMock(anObject);

/* run code under test */

OCMVerify([partialMocksomeMethod]);

Verification is done in the same way as with class and protocol mocks. As described just above, calls using a reference to the real object are intercepted, too. There is no need to insure that a reference to the mock is used, calls can be made using references to the real object.

譯:驗證后以同樣的方式與mock類和協(xié)議。上方,所述調用使用攔截,對真實對象的引用。不需要確保使用mock的引用,稱可以通過對真實對象的引用。

6.3 Restoring the object(恢復的對象)

idpartialMock=OCMPartialMock(anObject);

/* do stuff */

[partialMock stopMocking];

The real object can be returned to its original state by callingstopMocking. This is only necessary if the original state must be restored before the end of the test. The partial mock automatically callsstopMockingduring its own deallocation.

譯:真正的對象可以通過調用stopMocking回到初始狀態(tài)。這僅僅是必要的,如果必須在結束前恢復原始狀態(tài)測試。部分mock自動調用stopMocking期間自己的回收。

When the object is returned to its original state, its class will be switched back to the original class. This effectively removes all the stubs. However, this also makes it impossible for the partial mock to add new stubs or to verify interactions. You should really not use a partial mock after having calledstopMocking.

譯:當對象返回到原來的狀態(tài),它的類將切換回原始類。這將有效消除所有的存根。然而,這也使得部分模擬無法添加新存根或驗證交互。你應該不使用部分模擬稱為stopMocking后。

7 Strict mocks and expectations(嚴格的Mock和期望)

7.1 Expect-run-verify(期望-運行-驗證)

idclassMock=OCMClassMock([SomeClassclass]);

OCMExpect([classMocksomeMethodWithArgument:[OCMArgisNotNil]]);

/* run code under test, which is assumed to call someMethod */

OCMVerifyAll(classMock)

This is the original approach to mocking. First the mock object is set up with expectations, then the code under test is run, and afterwards the expectations are verified. If an expected method has not been invoked, or has not been invoked with the right arguments, then an error is reported. As shown it is possible to useargument constraintsin the expect statement. Strict mocks can be created for classes and protocols.

譯:這是原始的mock方法。第一次模擬對象設置期望,然后運行測試代碼,驗證之后的期望。如果預期的方法沒有被調用,或者沒有正確的調用參數,然后會報告一個錯誤。如圖所示是可能期望語句中使用參數約束。嚴格的mock可以創(chuàng)建類和協(xié)議。

If in doubt use the newerverify-after-runningapproach described inVerifying interactions.

譯:如果在懷疑使用較新的verify-after-running方法驗證中所描述的交互

7.2 Strict mocks and failing fast(嚴格mock 與 快速失?。?/h2>

idclassMock=OCMStrictClassMock([SomeClassclass]);

[classMock someMethod];

//thiswillthrowanexception

The mock has been set up as a strict mock without any expectations. CallingsomeMethodwill cause the mock to throw an exception. This is also known asfailing fastbecause the test fails immediatly when the unexpected call is made. Only strict mocks fail fast.

譯:mock被設置為一個嚴格模擬沒有任何期望。調用someMethod將導致mock拋出異常。這也被稱為快速地失敗,因為測試失敗馬上當意想不到的調用。只有嚴格的mock快速失敗

7.3 Stub actions and expect(stub 行為 與期望)

idclassMock=OCMStrictClassMock([SomeClassclass]);

OCMExpect([classMocksomeMethod]).andReturn(@"a string for testing");

/* run code under test, which is assumed to call someMethod */

OCMVerifyAll(classMock)

It is possible to useandReturn,andThrow, etc with expectations, too. This will then run the stub action if and when the method is invoked and, on verify, ensure that the method was actually invoked.

譯:可以使用andReturn、規(guī)劃等與預期。然后運行stub行動如果和調用方法時,在驗證,確保實際上是調用的方法。

7.4 Verify with delay(驗證與延遲)

idmock=OCMStrictClassMock([SomeClassclass]);

OCMExpect([mocksomeMethod]);

/* run code under test, which is assumed to call someMethod eventually */

OCMVerifyAllWithDelay(mock,aDelay);

In certain cases the expected method will only be called when the run loop is active. For these cases it is possible to delay the verification for a while. Note thataDelay(expressed asNSTimeInterval) is the maximum the mock will wait. It normally returns as soon as the expectations have been met.

譯:在某些情況下預期的方法只會調用運行循環(huán)時活躍。在這些情況下,有可能延遲驗證一段時間。注意,aDelay(表示為NSTimeInterval)是最大的模擬等。它通常返回一旦已達到預期。

7.5 Verifying in order

idmock=OCMStrictClassMock([SomeClassclass]);

[mocksetExpectationOrderMatters:YES];

OCMExpect([mocksomeMethod]);

OCMExpect([mockanotherMethod]);

// calling anotherMethod before someMethod will cause an exception to be thrown? 之前調用anotherMethod someMethod會導致拋出一個異常

[mockanotherMethod];

The mock can be told to verify that expected methods are called in the same order as the expectations are set up. As soon as a method is called that is not next on the “expected list” the mock will fail fast and throw an exception.

譯:模擬可以告訴確認預計方法的預期設置的順序相同。當一個方法被調用,不是下一個“期望列表”模擬將快速失敗,拋出一個異常。

8 Observer mocks

8.1 Setup

idobserverMock=OCMObserverMock();

[notificatonCenteraddMockObserver:aMockname:SomeNotificationobject:nil];

[[mockexpect]notificationWithName:SomeNotificationobject:[OCMArgany]];

Creates a mock object that can be used to observe notifications, registers it with a notification center, and tells the mock to expectSomeNotificationwith any object.

譯:創(chuàng)建一個模擬對象,可以用來觀察通知,注冊通知中心,并告訴模擬期望SomeNotification與任何對象。

8.2 Verification

OCMVerifyAll(observerMock);

Currently observer mocks are always strict, they will raise an exception when an unexpected notification is received. This implies that individual notifications cannot be verified after the fact. All notifications must be set up with expect, and they are verified together after the code under test has run usingOCMVerifyAll.

譯:目前觀察者mock總是嚴格,他們將意外收到通知時引發(fā)異常。這意味著個人通知不能驗證后的事實。所有的通知都必須設置期望,他們一起驗證代碼在測試后usingOCMVerifyAll運行。

9 Advanced topics(高級主題)

9.1 Failing fast for regular (nice) mocks(沒有快速的定期(nice)模擬)

On a strict mock object, when a method is called that has not been mocked (using some variant of stub or expect) the mock object will raise an exception. It willfail fast. Regular mock objects simply return the default value for the return type. Regular mocks can be configured on a per-method basis to fail fast:

譯:嚴格的mock對象,當一個方法被調用,沒有mock(使用stub或期望的一些變體)mock對象將引發(fā)一個異常。它會很快失敗。常規(guī)mock對象僅僅返回返回類型的默認值。常規(guī)模擬可以配置在每個方法的基礎上快速失敗:

idmock=OCMClassMock([SomeClassclass]);

OCMReject([mocksomeMethod]);

In this case the mock will accept all methods exceptsomeMethod; if that is invoked the mock will throw an exception.

譯:在這種情況下,mock將接受所有方法exceptsomeMethod;如果這是調用模擬將拋出一個異常。

9.2 Re-throwing fail fast exceptions in verify all(驗證所有拋出收到快速失敗異常)

In fail-fast mode an exception might not cause the test to fail. This can happen when the call stack for the method does not end in the test. Fail fast exceptions will be re-thrown whenOCMVerifyAllis called. This makes it possible to ensure that unwanted invocations from notifications etc. can be detected.

譯:在快速失敗模式異??赡懿粫е聹y試失敗。這可能發(fā)生在調用堆棧的方法并不在測試結束??焖偈‘惓e-thrown whenOCMVerifyAllis調用。這可以確保不必要的調用從通知等可以被檢測出來。

9.3 Stubbing methods that create objects(stub創(chuàng)建對象的方法)

idclassMock=OCMClassMock([SomeClassclass]);

OCMStub([classMockcopy])).andReturn(myObject);

It is possible to stub class and instance methods that conceptually create objects. OCMock automatically adjusts the reference count of the returned object when stubbing methods that have a name that begins withalloc,new,copy, ormutableCopy.

譯:是可能的stub類和實例概念上創(chuàng)建對象的方法。OCMock自動調整stub方法時返回的對象的引用計數的名稱始于alloc,新的副本,或者mutableCopy

idclassMock=OCMClassMock([SomeClassclass]);

OCMStub([classMocknew])).andReturn(myObject);

It possible, although not advisable, to stub outnewfor a class. If you find yourself doing this a lot, please consider thedependency injectionpattern.

譯:成為可能,盡管不明智,存根outnewfor類。如果你發(fā)現(xiàn)自己這樣做,請考慮thedependency injectionpattern。

IMPORTANT:It is not possible to stub theinitmethod, because that is implemented by the mock itself.

譯:重要:sub init方法是不可能的,因為這是由mock實現(xiàn)本身。

9.4 Instance-based method swizzling(基本于實例方法 swizzling)

In a nutshell,Method Swizzlingdescribes the replacement of a method implementation with a different implementation at runtime. Using partial mocks and theandCallaction OCMock allows such replacements on a per-instance basis.

譯:簡而言之,swizzling描述方法的替代方法在運行時實現(xiàn)使用不同的實現(xiàn)。完好無損地行動OCMock允許使用部分mock和替換每個實例基礎。

idpartialMock=OCMPartialMock(anObject);

OCMStub([partialMocksomeMethod]).andCall(differentObject,@selector(differentMethod));

After these two lines, whensomeMethodis sent toanObjectthe implementation of that method is not invoked. Instead,differentMethodis called ondifferentObject. Other instances of the same class are not affected; for these the original implementation ofsomeMethodis still invoked. The methods can have different names but their signatures should be the same.

譯:這兩條線后,當發(fā)送someMethod anObject不是調用的實現(xiàn)方法。相反,differentMethod呼吁differentObject。其他相同的類的實例不受影響;對這些原始someMethod仍然是調用的實現(xiàn)。方法可以有不同的名字,但他們的簽名應該是相同的。

10 Limitations(限制)

10.1 Only one mock at a time can stub class methods on a given class

//一次只有一個模擬stub類方法可以在給定的類

// don't do thisid

mock1=OCMClassMock([SomeClassclass]);

OCMStub([mock1 aClassMethod]);

idmock2=OCMClassMock([SomeClassclass]);

OCMStub([mock2 anotherClassMethod]);

As mentioned above, if the mock object that added a stubbed class method is not deallocated then the stubbed method will persist, even across tests. If multiple mock objects manipulate the same class at the same time the behaviour is undefined.

譯:如上所述,如果添加了一個stub類的mock對象方法不一致的方法將持續(xù)下去,甚至在測試。如果多個mock對象同時操作同一個類的行為是未定義的。

10.2 Setting up expect after stub on the same method does not work

//設置期望相同的方法stub后不工作

idmock=OCMStrictClassMock([SomeClassclass]);

OCMStub([mocksomeMethod]).andReturn(@"a string");

OCMExpect([mocksomeMethod]);

/* run code under test */

OCMVerifyAll(mock);

//willcomplainthatsomeMethodhasnotbeencalled

The code above first sets up a stub forsomeMethodand afterwards an expectation for the same method. Due to the way mock objects are currently implemented any calls tosomeMethodare handled by the stub. This means that even if the method is called the verify fails. It is possible to avoid this problem by addingandReturnto the expect statement. You can also set up a stub after the expect.

譯:上面的代碼首先設置一個stub someMethod后來一個期望相同的方法。由于目前mock對象的方式實現(xiàn)任何調用someMethod由stub。這意味著,即使方法稱為驗證失敗??梢员苊膺@個問題通過添加andReturn期望聲明。后你也可以 在期望前設置一個stub。

10.3 Partial mocks cannot be created for certain special classes

//部分mock為某些特殊類不能被創(chuàng)造

idpartialMockForString=OCMPartialMock(@"Foo");

// will throw an exception

NSDate*date=[NSDatedateWithTimeIntervalSince1970:0];

idpartialMockForDate=OCMPartialMock(date);

//willthrowonsomearchitectures

It is not possible to create partial mocks for instances of toll-free bridged class, e.g.NSString, or for objects represented with tagged pointers, e.g.NSDateon some architectures. The mock object will throw a descriptive exception should you try to do this.

譯:不可能為免費架橋類的實例創(chuàng)建局部mock,例如NSString,或者用標記表示指針的對象,例如NSDate架構。mock對象將拋出一個描述性的異常應該嘗試這樣做。

10.4 Certain methods cannot be stubbed or verified

//某些方法不能stubbed或驗證

idpartialMockForString=OCMPartialMock(anObject);

OCMStub([partialMockclass]).andReturn(someOtherClass);

//willnotwork

It is not possible to mock a number of core runtime methods. This includesinit, class, methodSignatureForSelector: ,forwardInvocation: , respondsToSelector:, and several others.

譯:不可能mock的核心運行時方法。這包括初始化、類methodSignatureForSelector:forwardInvocation:respondstoselectorismemberofclass:,和其他幾個。

Note thatclassis automatically stubbed to return the original class of the object, and not the dynamic subclass used by the partial mock.

譯:注意,類是自動的返回原始類的對象,而不是使用的動態(tài)子類部分模擬

10.5 Class methods on NSString and NSArray cannot be stubbed or verified

//類方法NSString和NSArray不能存根或驗證。

idstringMock=OCMClassMock([NSStringclass]);

// the following will not work

OCMStub([stringMockstringWithContentsOfFile:[OCMArgany]encoding:NSUTF8StringEncodingerror:[OCMArgsetTo:nil]]);

It is not possible to stub or verify class methods onNSStringandNSArray. Trying to do so has no effect.

譯:不可能onNSStringandNSArray stub類或驗證方法。試圖這么做沒有任何影響

10.6 Methods on NSObject cannot be verified(NSObject不能驗證的方法)

idmock=OCMClassMock([NSObjectclass]);

/* run code under test, which calls awakeAfterUsingCoder: */

OCMVerify([mockawakeAfterUsingCoder:[OCMArgany]]);

//stillfails

It is not possible useverify-after-runningwith methods implemented in NSObject or a category on it. In some cases it is possible to stub the method and then verify it. It is possible to useverify-after-runningwhen the method is overriden in a subclass.

譯:不可能useverify-after-runningwith方法實現(xiàn)NSObject或一個類別。在某些情況下可以stub方法并驗證??梢評severify-after-runningwhen子類的方法重載。

10.7 Private methods in core Apple classes cannot be verified

//核心蘋果類中的私有方法不能得到證實

UIWindow*window=/* get window somehow */

idmock=OCMPartialMock(window);

/* run code under test, which causes _sendTouchesForEvent: to be invoked */

OCMVerify([mock_sendTouchesForEvent:[OCMArgany]]);//stillfails

It is not possible useverify-after-runningwith private methods in core Apple classes. Specifically, all methods with an underscore prefix and/or suffix in a class with either NS or UI as prefix. In some cases it is possible to stub the method and then verify it.

譯:不可能stub或驗證類方法NSString和NSArray。試圖這么做沒有任何影響。

10.8 Verify-after-running cannot use a delay(Verify-after-running不能使用延遲)

It is currently not possible to verify a method with a delay. This is currently only possible using theexpect-run-verifyapproach described below instrict mocks and expectations.

譯:前不可能驗證方法有延遲。這是目前只可能使用下面描述的expect-run-verify方法嚴格mock和期望。

10.9 Using multiple threads in tests(在測試中使用多個線程)

OCMock is not fully thread-safe. Up to version 3.2.x OCMock was not thread-aware at all. Any combination of operations on a mock object from

multiple threads was likely to cause issues and make the test fail.

譯:OCMock沒有完全線程安全的。3.2版本。x OCMock不是thread-aware。的任意組合操作模擬對象從多個線程可能會導致問題,使測試失敗。

As of OCMock 3.3 it is still necessary to invoke all setup and verification operations from a single thread, preferrably the main thread of the test runner. It is possible, though, to use the mock object from multiple threads. The mock object can even be used from a different thread while its setup continues in the main thread. See#235for details.

譯:3.3 OCMock它仍然需要從一個線程調用所有設置和驗證操作,preferrably測試運行程序的主線程。這是有可能的,不過,從多個線程使用模擬對象。模擬對象甚至可以從一個不同的線程而設置仍在主線程。有關詳細信息,請參閱# 235。

More detail

The test cases inOCMockTests?show all uses and most edge cases.

Changes.txtcontains a chronological list of all changes.





最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • Spring Cloud為開發(fā)人員提供了快速構建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,502評論 19 139
  • 文/鐵骨柔情 娘在 家在 娘孕育了兒女們 臍帶雖斷開 可母子情深 從未割裂 娘是家里的魂 是在外兒女們 無時不刻的...
    鐵骨柔情青島閱讀 518評論 0 0
  • 大家好!仲陽智業(yè)向陽IN4袁軍,我是一個自信,付出,擔當的男人 在一個葡萄園內,一串串飽滿的大葡萄,讓人垂涎欲滴。...
    袁軍Sean閱讀 548評論 0 1
  • 很久沒有寫總結了,發(fā)現(xiàn)一段時間不總結,心里就是亂糟糟的,就像家里需要經常整理打掃一樣,思緒也是如此。很久不打理,就...
    隱身的小猴閱讀 352評論 0 0

友情鏈接更多精彩內容