This page describes the features present in OCMock 2.x, using the traditional syntax. All these features, including the selector-based syntax, are available in OCMock 3, too. However, starting with OCMock 3 the default is the modern syntax, described on the new reference page.

Class mocks

id mock = [OCMockObject mockForClass:[SomeClass class]]

Creates a mock object that can be used as if it were an instance of SomeClass.

Expectations and verification

[[mock expect] someMethod:someArgument]

Tells the mock object that someMethod: should be called with an argument that is equal to someArgument. After this setup the functionality under test should be invoked followed by

[mock verify]

The verify method will raise an exception if the expected method has not been invoked.

In some 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.

[mock verifyWithDelay:aDelay]

Note that aDelay is the maximum the mock will wait. It normally returns as soon as the expectation has been met.

Stubs

[[[mock stub] andReturn:aValue] someMethod:someArgument]

Tells the mock object that when someMethod: is called with someArgument it should return aValue.

If the method returns a primitive type then andReturnValue: must be used with a value argument. It is not possible to pass primitive types directly.

[[[mock stub] andReturnValue:@YES] aMethodReturnABoolean:someArgument]

Values can also be returned in pass-by-reference arguments:

[[mock stub] someMethodWithReferenceArgument:[OCMArg setTo:anObject]]
[[mock stub] someMethodWithReferenceArgument:[OCMArg setToValue:OCMOCK_VALUE((int){aValue})]]

In this case the mock object will set the reference that is passed to the method to anObject and aValue.

The mock object can also throw an exception or post a notification when a method is called:

[[[mock stub] andThrow:anException] someMethod:someArgument]
[[[mock stub] andPost:aNotification] someMethod:someArgument]

In fact, the notification can be posted in addition to returning a value:

[[[[mock stub] andPost:aNotification] andReturn:aValue] someMethod:someArgument]

The mock can delegate the handling of an invocation to a completely different method:

[[[mock stub] andCall:@selector(aMethod:) onObject:anObject] someMethod:someArgument]

In this case the mock object will call aMethod: on anObject when someMethod: is 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.

If Objective-C blocks are available a block can be used to handle the invocation and set up a return value:

void (^theBlock)(NSInvocation *) = ^(NSInvocation *invocation) {
/* code that reads and modifies the invocation object */
};
[[[mock stub] andDo:theBlock] someMethod:[OCMArg any]];

If using a partial mock (see below) it is possible to forward the method to the implementation in the real object, which can be useful to simply check that a method was called:

[[[mock expect] andForwardToRealObject] someMethod]

Note that it is possible to use andReturn:, andThrow:, etc with expect, too. This will then return the given return value and, on verify, ensure that the method has been called.

Class methods

[[[mock stub] andReturn:aValue] someClassMethod]

Tells the mock object that when someClassMethod is called on the class for which the mock object was created it should return aValue. This is the same syntax that is used to stub instance methods.

As with partial mocks it is possible to use andForwardToRealObject to invoke the actual class method implementation.

[[[mock expect] andForwardToRealObject] someClassMethod]

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, the intent to mock the class method must be made explicit:

[[[[mock stub] classMethod] andReturn:aValue] aMethod]

The class can be returned to its original state, i.e. all stubs will be removed:

[mock stopMocking]

This is only necessary if the original state must be restored before the end of the test. The mock automatically callsstopMocking during its own deallocation.

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

Argument constraints

[[mock expect] someMethod:[OCMArg any]]

Tells the mock object that someMethod: should be called and it does not matter what the argument is. This only works for object arguments.

Pointers and selectors require special treatment:

[[mock expect] someMethodWithPointerArgument:[OCMArg anyPointer]]
[[mock expect] someMethodWithSelectorArgument:[OCMArg anySelector]]

Arguments that are neither objects nor pointers or selectors cannot be ignored using an any placeholder (for details see thisforum thread). It is possible, though, to tell the mock to ignore all non-object arguments in an invocation:

[[[mock expect] ignoringNonObjectArgs] someMethodWithIntArgument:0]

In this case the mock will accept any invocation of someMethodWithIntArgument: 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 on OCMArg.

Other constraints available for object arguments are:

[[mock expect] someMethod:[OCMArg isNil]]
[[mock expect] someMethod:[OCMArg isNotNil]]
[[mock expect] someMethod:[OCMArg isNotEqual:aValue]]
[[mock expect] someMethod:[OCMArg checkWithSelector:aSelector onObject:anObject]]

The last constraint will, when the mock object receives someMethod:, send aSelector to anObject and if aSelector takes an argument will pass the argument that was passed to someMethod:. The method should return a boolean indicating whether the argument matched the expectation or not.

If Objective-C blocks are available it is possible to check the argument with a block as follows:

[[mock expect] someMethod:[OCMArg checkWithBlock:^BOOL(id value) { /* return YES if value is ok */ }]];

Last but not least it is also possible to use Hamcrest matchers like this:

[[mock expect] someMethod:startsWith(@"foo")]

Note that this will only work when the Hamcrest framework is explicitly linked by the unit test bundle.

Nice mocks / failing fast

When a method is called on a mock object that has not been set up with either expect or stub the mock object will raise an exception. This fail-fast mode can be turned off by creating a "nice" mock:

id mock = [OCMockObject niceMockForClass:[SomeClass class]]

While nice mocks will simply ignore all unexpected methods it is possible to disallow specific methods:

[[mock reject] someMethod]

Note that in fail-fast mode, if the exception is ignored, it will be rethrown when verify is called. This makes it possible to ensure that unwanted invocations from notifications etc. can be detected.

Protocol mocks

id aMock = [OCMockObject mockForProtocol:@protocol(SomeProtocol)]

Creates a mock object that can be used as if it were an instance of an object that implements SomeProtocol.

Partial mocks

id aMock = [OCMockObject partialMockForObject:anObject]

Creates a mock object that can be used in the same way as anObject. When a method that is not stubbed is invoked it will be forwarded to anObject. When a stubbed method is invoked using a reference to anObject, rather than the mock, it will still be handled by the mock.

The real object can be returned to its original state, i.e. all stubs will be removed:

[aMock stopMocking]

This is only necessary if the original state must be restored before the end of the test. The partial mock automatically callsstopMocking during its own deallocation.

Note that currently partial mocks cannot be created for instances of toll-free bridged classes, e.g. NSString.

Observer mocks

id aMock = [OCMockObject observerMock]

Creates a mock object that can be used to observe notifications. The mock must be registered in order to receive notifications:

[notificatonCenter addMockObserver:aMock name:SomeNotification object:nil]

Expectations can then be set up as follows:

[[mock expect] notificationWithName:SomeNotification object:[OCMArg any]]

Note that currently there is no "nice" mode for observer mocks, they will always raise an exception when an unexpected notification is received.

Instance-based method swizzling

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

id mock = [OCMockObject partialMockForObject:anObject]
[[[mock stub] andCall:@selector(differentMethod:) onObject:differentObject] someMethod:[OCMArg any]]

After these two lines, when someMethod: is sent to anObject the implementation of that method is not invoked. Instead,differentMethod: is called on differentObject. Other instances of the same class are not affected; for these the original implementation of someMethod: is still invoked. The methods can have different names but their signatures should be the same.

More detail

The test cases in OCMockObjectTests and OCMockObjectHamcrestTests show all uses of OCMock.

Changes.txt contains a chronological list of all changes.

Features (OCMock 2)的更多相关文章

  1. iOS单元測试:Specta + Expecta + OCMock + OHHTTPStubs + KIF

    框架选择 參考这篇选型文章,http://zixun.github.io/blog/2015/04/11/iosdan-yuan-ce-shi-xi-lie-dan-yuan-ce-shi-kuang ...

  2. Specific sleep staging features in EEG

    Source: MedScape Overview NREM and REM occur in alternating cycles, each lasting approximately 90-10 ...

  3. ECMAScript 6 Features 中文版

    ECMAScript 6 Features 中文版 如词不达意,欢迎提 PR & issue 采用中英混排的方式进行译制,如不解请查看对应原文 本文档将与原作者的 文档 保持同步更新,欢迎关注 ...

  4. New Features In SNMPv3 - SNMP Tutorial

    30.12 New Features In SNMPv3 We said that version 3 of SNMP represents an evolution that follows and ...

  5. 自然语言27_Converting words to Features with NLTK

    https://www.pythonprogramming.net/words-as-features-nltk-tutorial/ Converting words to Features with ...

  6. IOS单元测试,OCMock

    1.环境搭建 使用官方推荐,手动搭建.. 1.下载所需文件 http://ocmock.org/download/ 根据自己的需要下载不同的版本. 打开iOS library文件夹,里面就有需要用到的 ...

  7. Android真机调试 Android.Util.AndroidRuntimeException: You cannot combine custom titles with other title features

    参考连接:http://blog.csdn.net/scyatcs/article/details/9003285 Android.Util.AndroidRuntimeException: You ...

  8. [Android Tips] 22. Available Java 7 Features in Android

    This only allows Java 7 language features, and you can hardly benefit from anything since a half of ...

  9. ASP.NET features need application service database support

    搭建的web程序出现如上图所示的错误 原因程序使用以下ASP.NET 特性 Membership (the SqlMembershipProvider class). Role management ...

随机推荐

  1. HDU 3775 Chain Code pick定理

    pick定理:一个计算点阵中顶点在格点上的多边形面积公式:S=a+b÷2-1,其中a表示多边形内部的点数,b表示多边形边界上的点数,s表示多边形的面积. 思路:http://blog.csdn.net ...

  2. 软工实践 - 第十七次作业 Alpha 冲刺 (8/10)

    队名:起床一起肝活队 组长博客:https://www.cnblogs.com/dawnduck/articles/10023469.html 作业博客:班级博客本次作业的链接 组员情况 组员1(队长 ...

  3. 使用Bootstrap框架的HTML5页面模板

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  4. [BZOJ3196] 二逼平衡树 [权值线段树套位置平衡树]

    题面 洛咕题面 思路 没错我就是要不走寻常路! 看看那些外层位置数据结构,必须二分的,$O(n\log^3 n)$的做法吧! 看看那些cdq分治/树状数组套线段树的,空间$O(n\log^2 n)$挤 ...

  5. TJOI2018游记

    D1T1 - 数学计算 直接用线段树/平衡树维护所有数的积即可.我思想僵化写了一个数学方法...应该是能做\(\bmod\)所有数的乘除法. 时间复杂度\(O(nlogn)\). D1T2 - 智力竞 ...

  6. 洛谷 P3224 [HNOI2012]永无乡 解题报告

    P3224 [HNOI2012]永无乡 题目描述 永无乡包含 \(n\) 座岛,编号从 \(1\) 到 \(n\) ,每座岛都有自己的独一无二的重要度,按照重要度可以将这 \(n\) 座岛排名,名次用 ...

  7. 静态区间第k大 树套树解法

    然而过不去你谷的模板 思路: 值域线段树\([l,r]\)代表一棵值域在\([l,r]\)范围内的点构成的一颗平衡树 平衡树的\(BST\)权值为点在序列中的位置 查询区间第\(k\)大值时 左区间在 ...

  8. 一种简单高效的音频降噪算法示例(附完整C代码)

    近期比较忙, 抽空出来5.1开源献礼. 但凡学习音频降噪算法的朋友,肯定看过一个算法. <<语音增强-理论与实践>> 中提及到基于对数的最小均方误差的降噪算法,也就是LogMM ...

  9. server reached pm.max_children setting (5), consider raising it

    先查看日志 /data1/server/php-cgi/var/log/php-fpm.log[19-Dec-2012 11:41:13] WARNING: [pool www] server rea ...

  10. json数据格式的简单案例

    json数据是一种文本字符串,它是javascript的原生数据格式,在数据需要多次重复使用时,json数据是ajax请求的首先.(注:ajax返回的数据格式支持三种分别为:文本格式,json.和xm ...