Swapnil
Swapnil

Reputation: 1878

Mocking UIAlertView in Swift

I am writing XCTest cases in swift for my project which is in Objective C. I have method which shows alert view (which is deprecated, but I want to keep it as of now). I want to mock it for writing test cases in swift, but I am not getting it any way.

I am little bit familiar with OCMock and as I read, it is built in Objective C. In objective C, we can use OCMock classes to return expected result and to verify alert view show method. But how to do same in Swift? I tried writing same way like Objective C, but in swift it gives compiler error for some methods like "addReturn" from OCMock. This may be because OCMock uses Objective C runtime language features to create Mock, which is absent in swift.

-(void)showMyError {
   UIAlertView *alert = [[UIAlertView alloc]
   initWithTitle:@"Title"
   message:@"Please press a button."
   delegate:...
   cancelButtonTitle:@"Cancel"
   otherButtonTitles:@"OK", nil];

[alert show];

}

Is there any way so that I can write XCTestcases in Swift for above method?

Upvotes: 1

Views: 558

Answers (1)

dasdom
dasdom

Reputation: 14063

You can use dependency injection. To do this, create a protocol with the methods initWithTitle:message:delegate:cancelButtonTitle:otherButtonTitles: and show. Create a mock class conforming to that protocol. Inject the class object into the class that you want to test and instantiate of the injected class when you want to show the alert.

Upvotes: 1

Related Questions