似乎我第一次在 OCMock stub 上添加 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];
stub 方法在 [testEntity update] 中调用。但每次 stub 方法都返回速度1值,所以我猜想设置方法返回值的第二次尝试不会被接受。
有没有办法在 OCMock 中做到这一点?
最佳答案
当您 stub
一个方法时,您是说它应该始终以指定的方式运行,无论它被调用多少次。解决此问题的最简单方法是将 stub
更改为 expect
:
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];
或者,如果您需要 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];
关于unit-testing - 如何更改 OCMock stub 的返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5658501/