问题描述
|
似乎我第一次在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];
存根方法在[testEntity update]中调用。但是,每当有桩的方法每次都返回VeLocity1值时,我想都没有兑现第二次设置方法返回值的尝试。
有没有办法在Ocmock中做到这一点?
解决方法
当您“ 1”一个方法时,就是说它应该始终以指定的方式起作用,而不管它被调用了多少次。解决此问题的最简单方法是将
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];
另外,如果需要ѭ1(例如,如果可能根本不调用该方法),则可以重新创建模拟:
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];
,实际上,当您使用andReturn
或andReturnValue
时,当您使用stub
时,只会将返回值设置为石头。您可以随时使用方法“ 10”更改返回值。这是对expect
的改进,在expect
中,您需要知道方法将被调用多少次。这是完成此操作的代码段:
__weak TestClass *weakSelf = self;
[[[physics stub] andDo:^(NSInvocation *invocation) {
NSValue *result = [NSValue valueWithCGPoint:weakSelf.currentVelocity];
[invocation setReturnValue:&result];
}] getCurrentVelocity];
,虽然我认为CipherCom有正确的答案,但我发现自己更喜欢创建一个用于返回各种值的帮助器类。过去我对ѭ13有疑问。
@interface TestHelper : NSObject
@property (nonatomic,assign) CGPoint velocity;
- (CGPoint)getCurrentVelocity;
@end
@implementation TestHelper
- (CGPoint)getCurrentVelocity
{
return self.velocity;
}
@end
然后在测试类中,我将为TestHelper
创建一个私有成员变量,并在setUp
方法中执行以下操作:
self.testHelper = [TestHelper new];
[[[physics stub] andCall:@selector(getCurrentVelocity) onObject:self.testHelper]
getCurrentVelocity];
这样,在每个测试中,我都可以将速度设置为测试所需的速度。
self.testHelper.velocity = CGPointMake(100,200);
,多次调用时,andReturn
/andReturnValue
/andDo
都不会被覆盖。我的解决方法是向测试类添加属性,并使用该属性来控制模拟对象应返回的内容。例如,在模拟对象上具有isAvailable
属性的情况下,我的代码将如下所示:
@interface MyTest: XCTestCase
@property BOOL stubbedIsAvailable;
@end
@implementation MyTest
- (void)setUp {
[OCMStub([myMockedObject isAvailable]) andDo:^(NSInvocation invocation) {
BOOL retVal = self.stubbedIsAvailable;
[invocation setReturnValue:&retVal];
}
}
- (void)testBehaviourWhenIsAvailable {
self.stubbedIsAvailable = YES;
// test the unit
}
- (void)testBehaviourWhenIsNotAvailable {
self.stubbedIsAvailable = NOT;
// test the unit
}