Skip to content


Objective-CでクラスメソッドをMockする

OCMockは素晴らしいライブラリだと思いますが、クラスメソッドにMock/Stub設定できなくて(※)困る時があります。

※OCMockの使用例(http://svn.mulle-kybernetik.com/OCMock/trunk/Source/OCMockObjectTests.m)にないのでおそらくOCMockでは無理、もしくはまだ機能として組み込んでないんだろうと思います。

ただ、Objective-Cはセレクタ(メソッドの名前のようなもの)とメソッドの実装のマッピングを、ランタイムAPIを使って実行時に変更できるので、これを使えばやりたい事はだいたい実現できます。(Method Swizzlingというらしいです)

メソッド交換すると、おそらく実行されるコンテキスト(ローカル/インスタンス変数、self etc)が変わると思うので、モックが実行されたかをチェックするフラグは、テストクラスのクラスメソッドにしてます。

Posted in Programming. Tagged with , , .

One Response

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

Continuing the Discussion

  1. Alexander7 linked to this post on July 24, 2011

    buy@generic.LEVITRA” rel=”nofollow”>…

    Need cheap generic LEVITRA?…

Some HTML is OK

(required)

(required, but never shared)

or, reply to this post via trackback.