unit-testing - 如何更改 OCMock stub 的返回值?

标签 unit-testing ocmock

似乎我第一次在 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/

相关文章:

iphone - 使用 SenTestCase 添加新测试(新测试未显示在管理方案中)

iOS OCMock 带参数的回调方法

iphone - 从模拟方法崩溃返回 CGRect

java - 使用 GemFire 进行单元测试 - 最佳实践

Python 类和单元测试

unit-testing - VueComponent.mounted : TypeError: Cannot read property 'get' of undefined in mounted hook

objective-c - OCMock:模拟协议(protocol),排除可选方法

python - views.py 中的 Django 文档测试

ios - OCMock 模拟 UIImagePickerController

ios - 所有调用的 OCMock stub 类方法