Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Compare: Mocks and Stubs

Mocks-and-Stubs.md
... ... @@ -4,6 +4,7 @@
4 4
5 5 Mocks are objects that imitate a class, or look like they conform to a protocol. They let you focus on interaction behavior between objects before full implementations exist, and to isolate objects from dependencies that may be too expensive or unreliable to use when running specs.
6 6
  7 +```objective-c
7 8 id carMock = [Car mock];
8 9 [ [carMock should] beMemberOfClass:[Car class]];
9 10 [[carMock should] receive:@selector(currentGear) andReturn:theValue(3)];
... ... @@ -19,6 +20,7 @@ Mocks are objects that imitate a class, or look like they conform to a protocol.
19 20
20 21 id flyerNullMock = [KWMock nullMockForProtocol:@protocol(FlyingMachine)];
21 22 [flyerNullMock takeOff];
  23 +```
22 24
23 25 ### Null Mocks
24 26
... ... @@ -71,6 +73,7 @@ Stubbing message patterns:
71 73
72 74 Example:
73 75
  76 +```objective-c
74 77 id cruiser = [Cruiser cruiser];
75 78 [[cruiser stubAndReturn:theValue(42.0f)] energyLevelInWarpCore:7];
76 79 float energyLevel = [cruiser energyLevelInWarpCore:7];
... ... @@ -82,6 +85,27 @@ Example:
82 85 id mock = [Animal mock];
83 86 [mock stub:@selector(species) andReturn:@"P. tigris"];
84 87 [[mock.species should] equal:@"P. tigris"];
  88 +```
  89 +
  90 +### Capturing Arguments
  91 +
  92 +At times, you may want to capture an argument that is passed to mock object. For instance, the argument may be an object that did not implement `isEqual:` and it must be captured in order to be verified properly. Alternatively, and the most likely case, is that the mock receives a message where one of the arguments is a [block](http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/Blocks/Articles/bxOverview.html#//apple_ref/doc/uid/TP40007502-CH3-SW1) and it must be captured and invoked in order to verify the behavior of that block.
  93 +
  94 +Example:
  95 +
  96 +```objective-c
  97 + id robotMock = [KWMock nullMockForClass:[Robot class]];
  98 + KWCaptureSpy *spy = [robotMock captureArgument:@selector(speak:afterDelay:whenDone:) atIndex:2];
  99 +
  100 + [[[robotMock should] receive] speak:@"Goodbye"];
  101 +
  102 + [robotMock speak:@"Hello" afterDelay:2 whenDone:^{
  103 + [robotMock speak:@"Goodbye"];
  104 + }];
  105 +
  106 + void (^block)(void) = spy.argument;
  107 + block();
  108 +```
85 109
86 110 ### Advanced Stubs and Memory Management
87 111
Something went wrong with that request. Please try again.