EzDevInfo.com

OCMockito

Mockito for Objective-C: creation, verification and stubbing of mock objects

OCMockito capturing primitive types?

How do I use OCMockito to capture argument with primitive values?

MKTArgumentCaptor seems to be able to capture only object types? Xcode says "Incompatible pointer to integer conversion".


Source: (StackOverflow)

How to stub CocoaLumberjack or NSLog with OCMockito

I can stub/verify a class method, but I'm having difficulty with defined macros. I'm trying to test that one of my methods calls DDLogInfo.

It's defined like so in the CocoaLumberjack source

#define DDLogInfo(frmt, ...)    LOG_MAYBE(LOG_ASYNC_ENABLED, LOG_LEVEL_DEF, DDLogFlagInfo,    0, nil, __PRETTY_FUNCTION__, frmt, ##__VA_ARGS__)

thanks!


Source: (StackOverflow)

Advertisements

OCMockito verify with any arguments

I'm trying to verify that a function on a mock object is NOT called at all with ANY parameters.

The function on the object I'm mocking is...

- (void)registerUserWithUsername:(NSString*)username password:(NSString*)password;

I'd like to verify that the function is NOT called if the username is blank.

i.e.

[mockService registerUserWithUsername:@"" password:@"Password"];

[verify(mockService, never()) registerWithUsername:....... password:.......];

I'm just not sure what to put in the ...... bits?


Source: (StackOverflow)

Custom OCHamcrest matcher for OCMockito mock verfication

I am using OCHamcrest and OCMockito for unit testing an iOS project. I'm working my way toward understanding using custom matchers in a mock verification of a method expectation that takes parameters. In particular, I want to verify one of the parameters passed to the expected method, but I need to pull apart the passed parameter in order to do so. To demonstrate, here's what I have for the relevant part of my test method:

EAAccessory *accessory = mock([EAAccessory class]);
UIViewController <ZKSearchManagerDelegate> *mockController = 
    mockObjectAndProtocol(
        [UIViewController class], @protocol(ZKSearchManagerDelegate)
    );
[verify(mockController) 
        zkZSensorFound:isSensorWithAccessory(accessory) 
     fromSearchManager:_sm];

The -zkZSensorFound:fromSearchManager: takes an object that contains an EAAccessory as a property. In my custom matcher, I need to open up that object and examine that property to make sure it's the same object as accessory within this test method. It's easy enough to pass accessory into the matcher as I'm doing here, but how do I get at the actual object that is passed to the parameter for use inside of my matcher? Or, am I going about this all wrong?

Update

I've accepted the answer from @JonReid, as it's a much more elegant solution than what I've concocted. Nevertheless, I think what I was using (thanks to this blog post), could be useful elsewhere:

#import "ArgumentCaptor.h"

EAAccessory *accessory = mock([EAAccessory class]);
UIViewController <ZKSearchManagerDelegate> *mockController = 
    mockObjectAndProtocol(
        [UIViewController class], @protocol(ZKSearchManagerDelegate)
    );
ArgumentCaptor *captor = argCaptor();
[verify(_mockController) zkZSensorFound:(ZKZSensor *)captor 
                      fromSearchManager:is(sameInstance(_sm))];
ZKZSensor *sensor = captor.argument;
assertThat(sensor.accessory, is(_mockAccessory));

Source: (StackOverflow)

Verify that correct frame is set on subview

Intro

I'd like to test that the right frame is set on a views subview (which is injected as a mock).

However I can't seem to find a way to verify that the right CGRect is set

Current Attempt

-(void)testThatCorrectFrameIsSet {
  //Arrange
  MKTArgumentCaptor *argumentCaptor = [[MKTargumentCaptor alloc] init];
  self.sut.subView = mock([UIView class]);

  //Act
  [self.sut awakeFromNib];

  //Assert
  [[[MKTVerify(self.sut.subView) withMatcher:[argumentCaptor capture]] setFrame:CGSizeZero];

  expect([argumentCaptor.value CGRectValue].size.x).to.beCloseToWithin(42, 0.001);
}

What's going wrong

I get:

"NSInvalidArgumentException", "-[_NSInlineData CGRectValue]: unrecognized selector sent to instance 0x7af325c0"

Which makes me wonder how to correctly capture CGRect values

Side Note

I am aware of the fact that I could inject an actual UIView instead of a mocked one, however the actual code I'm testing prevents me from doing this for reasons that would make this question harder than needed.


Source: (StackOverflow)

OCHamcrest matcher parameter is incompatible with Mockito mock at Verify

with the following unit test I'm using Mockito to mock NSUserDefaults but when I try to verify using OCHamcrest matcher to test that the param is an instance of an NSDictionary I get the warning:

Sending 'id{HCMatcher}' to parameter of incompatible type 'NSDictionary *'

NSUserDefaults *userDefaultsMock = mockClass([NSUserDefaults class]); 
//OR -- NSUserDefaults *userDefaultsMock = mock([[NSUserDefaults standardUserDefaults]class]);

Engineer *sut = [[Engineer alloc]init];

[given([userDefaultsMock stringForKey:@"engineerId"]) willReturn:@"02345"];

BOOL result = [sut setCurrentEngineerId:@"02345" userDefaults:userDefaultsMock];
[verify(userDefaultsMock) registerDefaults:instanceOf([NSDictionary class])];

Thanks


Source: (StackOverflow)

Questions about OCMockito setup with Cocoapods

I'm having troubles setting up OCMockito (and OCHamcrest) with Cocoapods on Xcode 5. This is my Podfile:

platform :ios, '5.0' 
pod 'RestKit', '~> 0.20.0'
pod 'OCMockito', '~> 1.0.0'
link_with ['WeatherApp', 'WeatherAppTests']

When I try to follow iOS Project Setup (https://github.com/jonreid/OCMockito#adding-ocmockito-to-your-project), Xcode can't find this imports:

#define HC_SHORTHAND
#import <OCHamcrestIOS/OCHamcrestIOS.h>

#define MOCKITO_SHORTHAND
#import <OCMockitoIOS/OCMockitoIOS.h>

So I tried to do this insted:

#define HC_SHORTHAND
#import <OCHamcrest/OCHamcrest.h>

#define MOCKITO_SHORTHAND
#import <OCMockito/OCMockito.h>

It's working, but I don't know if that's fine.

Also, I have another question. As far as I understand, I'm linking RestKit and OCMockito to both my main target and my test target. Is it possible to link RestKit on both targets but link OCMockito only to the test target?

Thanks in advance for the help.

UPDATE:

This is the Pods.xcconfig generetad by Cocoapods:

GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1
HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers" "${PODS_ROOT}/Headers/AFNetworking" "${PODS_ROOT}/Headers/OCHamcrest" "${PODS_ROOT}/Headers/OCMockito" "${PODS_ROOT}/Headers/RestKit" "${PODS_ROOT}/Headers/RestKit/RestKit" "${PODS_ROOT}/Headers/RestKit/RestKit/CoreData" "${PODS_ROOT}/Headers/RestKit/RestKit/Network" "${PODS_ROOT}/Headers/RestKit/RestKit/ObjectMapping" "${PODS_ROOT}/Headers/RestKit/RestKit/Support" "${PODS_ROOT}/Headers/SOCKit" "${PODS_ROOT}/Headers/TransitionKit"
OTHER_LDFLAGS = -ObjC -framework CFNetwork -framework CoreData -framework CoreGraphics -framework MobileCoreServices -framework Security -framework SystemConfiguration
PODS_ROOT = ${SRCROOT}/Pods

It seems that the IOS headers aren't setup correctly, is the pod wrong then?

UPDATE:

This are the contents of Pods/Headers/OCMockito

Pods/Headers/OCMockito


Source: (StackOverflow)

OCMockito crash when mocking KVO observer

I'm trying to mock an object that is passed to my SUT. When passed, the SUT registers the mock as observer for some properties. In SUT dealloc, it calls removeObserver on the mock. This was working just fine with OCMockito 0.23, but when updating to 1.0.0, this test makes OCMockito to get trapped in [HCIsEqual .cxx_destruct]. Debugging a little bit, lead me to MKTInvocationContainer method:

- (void)setInvocationForPotentialStubbing:(NSInvocation *)invocation

in which the invocation is told to retain its arguments. Could be a retain cycle?

Furthermore, I've been doing some research and I found several SO answers stating the incompatibility between NSProxy and KVO:

NSProxy and Key Value Observing

http://stackoverflow.com/a/17457155/2824409

However, I wonder why this was working with OCMockito 0.23 and not now. Any idea?

The solution in my case is to replace the mock with a real object. This works fine, but it is painful to build a whole object for a test suite that barely uses it.

At any case, if KVO is not supported with mocks, I believe this should be documented, and properly handled.

[EDIT]

I found a workaround for this problem.

We are using a custom block based KVO infrastructure, similar to the described here: http://www.mikeash.com/pyblog/key-value-observing-done-right.html. Now, SUT is registering the mock for KVO, passing self inside a block. I believe self is being retained somewhere, but it shouldn't be, since it is weakified before the block...

Using the default kvo framework provided by Apple seems to fix this problem. However, I'm still worried about the underlying problem. What changed in OCMockito that makes this fail now?

Anyway, sorry for the trouble and thank you very much.


Source: (StackOverflow)

Is there an idiomatic Objective-C technique to make an init method return a stub implementation for testing?

I am writing a unit test for a class Foo, which has a collaborator, Bar. I want to use a manually-built stub implementation of Bar in Foo's test.

If I were doing this in Java, I would give Foo a BarFactory collaborator and inject a MockBarFactory in Foo's test that always returned my StubBar.

I know this technique will work fine in Objective-C but it doesn't strike me as a particularly idiomatic thing to do in a dynamic language. I am wondering if I can do anything tricky that will cause [[Bar alloc] init] to return StubBar while I'm running my unit test but give me the normal implementation of Bar in "real life".

Or is the obvious factory pattern the most appropriate thing to use in this case?


Source: (StackOverflow)

Can OCMockito stub a method that takes a `const void *` parameter?

My MessageSerializer class has a method whose signature looks like this:

- (Message *)deserialize:(const void *)buffer length:(NSUInteger)length;

Can I use OCMockito to stub it? Where serializer is my mock serializer, the compiler approves of all these following forms in my test method:

[given([serializer deserialize:[data bytes] length:[data length]]) willReturn:message];
[given([serializer deserialize:(__bridge const void *)anything() length:[data length]]) willReturn:message];
[given([serializer deserialize: CFBridgingRetain(anything()) length:[data length]]) willReturn:message];

... but none of them cause the mock to return "message" to the class under test when deserialize:length: is called.


Source: (StackOverflow)

Unit test case for call back methods ios

I have a following method in my app for which I need to write unit test cases.
Can anyone suggest how can I test whether the success block or error block is called.

- (IBAction)loginButtonTapped:(id)sender
{
    void (^SuccessBlock)(id, NSDictionary*) = ^(id response, NSDictionary* headers) {
        [self someMethod];
    };

    void (^ErrorBlock)(id, NSDictionary*, id) = ^(NSError* error, NSDictionary* headers, id response) {
        // some code
    };

    [ServiceClass deleteWebService:@“http://someurl"
                              data:nil
                  withSuccessBlock:SuccessBlock
                    withErrorBlock:ErrorBlock];
}

Source: (StackOverflow)

OCMockito - mocked class with "willReturn" returns nil rather than the value I specify

The code I'm working with looks something like this:-

- (MyOrange *) getAnOrangeFromBowl:(MyBowl *)bowl withSize:(NSString *)size
{
    MyOrange *orange = [bowl getAnOrangeWithSize:size];
    return orange;
}

Before you ask, no I can't just call my "MyBowl" object's method directly, it needs to be done this way for reasons unrelated to this problem.

So, I want to test that within the above method, [bowl getAnOrangeWithSize] is being called with certain parameters. I want to mock the MyBowl class as its not what's under test here, only the above method is. I also want the [bowl getAnOrangeWithSize] call to return a mock of MyOrange - in this example just for comparison purposes, but potentially I might also be doing stuff with that "orange" in the method above & I'd want to write tests on that too.

To test this I want to inject a dependency (MyBowl mock) that in turn injects another mocked dependency (MyOrange). I've run across this requirement several times and have refactored to work around it, but in this case I'm stuck.

Anyway, the test I have is:-

- (void)testThatGetAnOrangeFromBowlIsReturningAValidOrange
{
    MyOrange *mockOrange = mock([MyOrange class]);
    MyBowl *mockBowl = mock([MyBowl class]);

    [given([mockBowl getAnOrangeWithSize:@"large"]) willReturn:mockOrange];
    MyOrange *returnedOrange = [sut getAnOrangeFromBowl:mockBowl withSize:@"large"];

    assertThat(returnedOrange, is(equalTo(mockOrange)));
}

The test fails, as returnedOrange is nil. Putting a breakpoint in the code, I can see that the call to "getAnOrangeWithSize" is returning nil, so it is apparently taking no notice of the given/willReturn instructions that I specified.

I've been searching documentation & scratching my head for a while on this trying various ideas but without luck. Is there a way to get the test working, or is this something OCMockito doesn't really support (and if so, can Kiwi handle this problem)? Thanks in advance.

EDIT: It seems its possible to do this in Kiwi, as shown below:-

it(@"should return a valid Orange", ^{
    id mockOrange = [MyOrange mock];
    id mockBowl = [MyBowl mock];

    [mockBowl stub:@selector(getAnOrangeWithSize:) andReturn:mockOrange];

    MyOrange *returnedOrange = [sut getAnOrangeFromBowl:mockBowl withSize:@"whatever"];
    [[returnedOrange should] equal:mockOrange];
});

If calls to methods inside mockOrange occur in the sut's code, mockOrange could be setup as a nullMock or stubs created to handle those calls.

I am very new to Kiwi, so the above may not be optimal. I also haven't found out yet how to create a stub that only works with certain argument values passed in, so that you could create one for (using the above example) a size of @"large" returning one MyOrange instance, and @"mouldy" returning another - but I suppose that's a topic for another question if I can't find how its done.

I'd still very much like to know the OCMockito/Hamcrest equivalent of the above Kiwi code, so I'll leave this as Unanswered for now.


Source: (StackOverflow)

OCMockito mocking calls with block

I want to mock an object with the following message declaration:

- (void)createWithCompletion:(void (^)(FuseResult *result, NSError *err)) completion;

Is it possible to mock the block call this message has to handle?

I read the ArgumentCaptorTest which has block but I wasn't sure if it's relevant.


Source: (StackOverflow)

Mock internal calls of a another class methods

I am trying to learn unit testing with ocmock. I am finding it difficult to mock calls of another class from a class which i am unit testing.

Can some one suggest how to make mock call to KeyChainUtils class and HttpRequest class:

Code to unit test with OCMock:

@implementation UserProfileService {
+(BOOL) isValidUser
{
    NSString* userId = [KeyChainUtil loadValueForKey:USER_ID]; //mock this call
    bool isValidUser = NO;
    if(userId && userId.length > 0){
        NSDictionary* response = [HTTPDataService getJSONForURL:@"http://xtest.com/checkuserid" forRequestData:@{@"userid": userId}];

        if(response && response[@"valid"]){
            isValidUser = [response[@"valid"] boolValue];             
        }else{
            NSLog(@"error in connecting to server. response => %@", response);
        }
    }
    return isValidUser;
 }
}

Source: (StackOverflow)

OcMock vs OcMockito - what are pros and cons

For iOS tdd testing/mocking which framework would you recommend ? i heard that OcMock has been around longer and is more lite weight. Could anyone provide a few examples of the pros and cons or demo some strengths of each. I'm just looking for a standard mocking framework thats fast but i'd like to know all the drawbacks/benefits of each.


Source: (StackOverflow)