2010-12-05 13 views
27

Estoy usando OCMock 1.70 y estoy teniendo un problema burlando un método simple que devuelve un valor BOOL. Aquí está mi código:Stub a Método que devuelve un BOOL con OCMock

@interface MyClass : NSObject 
- (void)methodWithArg:(id)arg; 
- (BOOL)methodWithBOOLResult; 
@end 
@implementation MyClass 
- (void)methodWithArg:(id)arg { 
    NSLog(@"methodWithArg: %@", arg); 
} 
- (BOOL)methodWithBOOLResult { 
    NSLog(@"methodWithBOOLResult"); 
    return YES; 
} 
@end 

- (void)testMock { 
    id real = [[[MyClass alloc] init] autorelease]; 
    [real methodWithArg:@"foo"]; 
    //=> SUCCESS: logs "methodWithArg: foo" 

    id mock = [OCMockObject mockForClass:[MyClass class]]; 
    [[mock stub] methodWithArg:[OCMArg any]]; 
    [mock methodWithArg:@"foo"]; 
    //=> SUCCESS: "nothing" happens 

    NSAssert([real methodWithBOOLResult], nil); 
    //=> SUCCESS: logs "methodWithBOOLResult", YES returned 

    BOOL boolResult = YES; 
    [[[mock stub] andReturn:OCMOCK_VALUE(boolResult)] methodWithBOOLResult]; 
    NSAssert([mock methodWithBOOLResult], nil); 
    //=> FAILURE: raises an NSInvalidArgumentException: 
    // Expected invocation with object return type. 
} 

¿Qué estoy haciendo mal?

Respuesta

60

Es necesario utilizar andReturnValue: no andReturn:

[[[mock stub] andReturnValue:OCMOCK_VALUE(boolResult)] methodWithBOOLResult]; 
5

Consejo: andReturnValue: acepta cualquierNSValue - especialmente NSNumber. Para agilizar más rápidamente los métodos con valores de retorno primitivos/escalares, omita por completo la declaración de variables locales y use [NSNumber numberWithXxx:...].

Por ejemplo:

[[[mock stub] andReturnValue:[NSNumber numberWithBool:NO]] methodWithBOOLResult]; 

de puntos de bonificación-auto boxeo, puede utilizar la sintaxis literal número (Clang docs):

[[[mock stub] andReturnValue:@(NO)] methodWithBOOLResult]; 
[[[mock stub] andReturnValue:@(123)] methodWithIntResult]; 
[[[mock stub] andReturnValue:@(123.456)] methodWithDoubleResult]; 
etc. 
+1

Las versiones más nuevas de OCMock deberían permitir que OCMOCK_VALUE también funcione en constantes; '' 'OCMOCK_VALUE (NO)' '', '' '@ NO''', y' '' @ (NO) '' 'deberían funcionar. –

1

estoy usando la versión 3.3.1 de OCMock y esta sintaxis funciona para mí:

SomeClass *myMockedObject = OCMClassMock([SomeClass class]); 
OCMStub([myMockedObject someMethodWithSomeParam:someParam]).andReturn(YES); 

Véase el OCMock documentation por ejemplo más.

Cuestiones relacionadas