Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OCMock mocking UIImagePickerController

I'm trying to mock UIImagePickerController to test method from ViewController (written in Swift):

var imagePicker: UIImagePickerController!

...

func choosePhoto() {
    imagePicker = UIImagePickerController()
    imagePicker.delegate = self
    imagePicker.sourceType = .PhotoLibrary
    self.presentViewController(imagePicker, animated: true, completion: nil)
}

and the test class (written in Objective-C):

Interface:

@property (nonatomic, strong) ViewController *viewController;

Implementation:

- (void)setUp {
    [super setUp];

    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    UINavigationController *navigationController = [storyboard instantiateInitialViewController];
    self.viewController = (ViewController *)[navigationController visibleViewController];
    self.viewController.view;
}

....

- (void)testPicker {
    id mockPicker = [OCMockObject mockForClass:[UIImagePickerController class]];
    self.viewController.imagePicker = mockPicker;

    [[mockPicker expect] setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
    [[(id)self.viewController expect] presentViewController:mockPicker animated:YES completion:nil];

    [self.viewController choosePhoto];

    [mockPicker verify];
}

The test fails, because:

OCMockObject(UIImagePickerController): expected method was not invoked: setSourceType:0

and

failed: caught "NSInvalidArgumentException", "-[MyApp.ViewController expect]: unrecognized selector sent to instance 0x....

Can anyone help me with this?

Many thanks.

like image 602
jonaszmclaren Avatar asked Jan 19 '26 02:01

jonaszmclaren


1 Answers

So, to use the expect method from OCMock, you have to have a mock of the object that is expecting a method call. In this case, you need to have a mock for self.myViewController - the ViewController class you're using doesn't have an expect method, so its getting confused. The fact that you're casting the VC to an id is masking the issue.

like image 70
bplattenburg Avatar answered Jan 21 '26 16:01

bplattenburg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!