Question

I am trying to write a unit test case for calculator in Xcode, currently I am writing test case for the add function.
This is my digit pressed function:

- (IBAction)digitPressed:(UIButton *)sender.

I have seen an example where if the method name is

- (IBAction)digitPressed:(id)sender,     

you can invoke the function with help of view tag like

[calc_view_controller digitPressed:[calc_view viewWithTag:6];   

The instance defined above in implementation section as

app_delegate         = [[UIApplication sharedApplication] delegate];
calc_view_controller = app_delegate.viewController;
calc_view            = calc_view_controller.view;

now since my button type is (UIButton *) I cant use view tag, is there any other alternative for UIButton type?
If so, Can you give me an example?

Was it helpful?

Solution

A button is a view, so -viewWithTag: will find it just fine. The only issue is your sender type not agreeing with the type returned by -viewWithTag:, but you can solve that with a cast if you're sure the view you'll get back is a button, or you can check first:

[calc_view digitPressed:(UIButton*)[calc_view viewWithTag:6]];

or:

UIButton *button = (UIButton*)[calc_view viewWithTag:6]];
if ([button isKindOfClass:[UIButton class]]) {
    [calc_view digitPressed:button];
}

Either works in practice; the latter is safer and makes it easy to add an additional test: you could fail the test if the button isn't a UIButton.

OTHER TIPS

You do it in the bad way, you shouldn't compare sender.titleLabel.text. Think about what happens when you'll change the label text, because e.g you must ship your app in another language.

But if you still want to handle button recognizing in that way, you have to create UIButton in your unit test and set it the proper label text value.

Rather than invoking the IBAction method, I would invoke the specific method which peforms the addition.

There are a number of things that you could test here, for example:

  1. The UIButton object sends the correct value to the digitPressed method
  2. The digitPressed method correctly extracts the value from the UIButton object and passes this value to the add method
  3. The result of the add method is what you expect

How much you test is up to you, personally I wouldn't get too hung up on 1 and 2. If the logic is wrong in either of these it will become obvious, and they are unlikely to attract regressions.

To me it is more important to fully test the add method. Send in plenty of common cases, edge cases and boundary values, rather than worrying about the flow from the UIButton press.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top