如何更改OCMock存根的返回值?

Cri*_*ris 25 unit-testing ocmock

看来我第一次在OCMock存根上添加andReturnValue时,返回值就是一成不变的.例如:

id physics = [OCMockObject niceMockForClass:[DynamicPhysicsComponent class]
Entity *testEntity = [Entity entityWithPhysicsComponent:physics];
CGPoint velocity1 = CGPointMake(100, 100);
CGPoint velocity2 = CGPointZero;
[[[physics stub] andReturnValue:OCMOCK_VALUE(velocity1)] getCurrentVelocity];
[testEntity update:0.1];
[[[physics stub] andReturnValue:OCMOCK_VALUE(velocity2)] getCurrentVelocity];
[testEntity update:0.1];
Run Code Online (Sandbox Code Playgroud)

在[testEntity update]中调用stubbed方法.但每次stubbed方法返回velocity1值,所以我猜第二次尝试设置方法的返回值是不值得的.

有没有办法在OCMock中做到这一点?

Chr*_*lay 37

当你使用stub一个方法时,你会说它应该始终以指定的方式运行,无论它被调用多少次.解决此问题的最简单方法是更改stubexpect:

CGPoint velocity1 = CGPointMake(100, 100);
CGPoint velocity2 = CGPointZero;
[[[physics expect] andReturnValue:OCMOCK_VALUE(velocity1)] getCurrentVelocity];
[testEntity update:0.1];
[[[physics expect] andReturnValue:OCMOCK_VALUE(velocity2)] getCurrentVelocity];
[testEntity update:0.1];
Run Code Online (Sandbox Code Playgroud)

或者,如果您需要stub(例如,如果可能根本不调用该方法),您可以重新创建模拟:

CGPoint velocity1 = CGPointMake(100, 100);
CGPoint velocity2 = CGPointZero;
[[[physics stub] andReturnValue:OCMOCK_VALUE(velocity1)] getCurrentVelocity];
[testEntity update:0.1];
[physics verify];

physics = [OCMockObject mockForClass:[Physics class]];
[[[physics stub] andReturnValue:OCMOCK_VALUE(velocity2)] getCurrentVelocity];
[testEntity update:0.1];
[physics verify];
Run Code Online (Sandbox Code Playgroud)

  • 在你的第二个例子中,当与stubbed方法一起使用时,"verify"的目的是什么? (2认同)

Pat*_*rik 26

实际上,stub如果您使用andReturn或只是设置返回值andReturnValue.您可以随时使用该方法andDo更改返回的值.这是一个改进expect,你需要知道一个方法被调用多少次.这里是完成此任务的代码片段:

__weak TestClass *weakSelf = self;
[[[physics stub] andDo:^(NSInvocation *invocation) {
    NSValue *result = [NSValue valueWithCGPoint:weakSelf.currentVelocity];
    [invocation setReturnValue:&result];
}] getCurrentVelocity];
Run Code Online (Sandbox Code Playgroud)

  • 我更喜欢这个答案,因为你没有强制执行必须调用stubbed方法的次数(如-expect). (3认同)