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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With