How to I capture an argument sent to a mock?

江枫思渺然 提交于 2019-12-22 05:48:08

问题


Does anyone know how to capture an argument sent to an OCMock object?

id mock = [OCMockObject mockForClass:someClass]
NSObject* captureThisArgument;
[[mock expect] foo:<captureThisArgument>]

[mock foo:someThing]
GHAssertEquals[captured, someThing, nil];

How do I go about validating the argument to foo? I'm happy to do it within a block in the mock definition too, but if I could get the object out so that I can assert on feature of it later that would be brilliant.

Is this possible with OCMock?


回答1:


If you want to validate your parameter maybe you can do it directly while you are setting your stub with something like :

id mock = [OCMockObject mockForClass:someClass];
NSObject* captureThisArgument;
[[mock expect] foo:[OCMArg checkWithBlock:^(id value){ 
    // Capture argument here...
}]];

Regards, Quentin A




回答2:


You can stub the call and pass it to a block that verifies it:

NSObject *expected = ...;

id mock = [OCMockObject mockForClass:someClass]
void (^theBlock)(NSInvocation *) = ^(NSInvocation *invocation) {
    NSObject *actual;
    [invocation getArgument:&actual atIndex:2];
    expect(actual).toEqual(expected);   
};
[[[mock stub] andDo:theBlock] foo:[OCMArg any]];

[mock foo:expected];

There's also a callback version of this, but the control flow gets more complex, as you need a state variable that's visible to both your test and the verification callback:

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


来源:https://stackoverflow.com/questions/10292551/how-to-i-capture-an-argument-sent-to-a-mock

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!