iosxctestocunit

Is it possible to test IBAction?


It is kinda easy to unit test IBOutlets, but how about IBActions? I was trying to find a way how to do it, but without any luck. Is there any way to unit test connection between IBAction in a View Controller and a button in the nib file?


Solution

  • I did it using OCMock, like this:

    MyViewController *mainView =  [[MyViewController alloc] initWithNibName:@"MyViewController" bundle:nil];
    [mainView view];
    
    id mock =  [OCMockObject partialMockForObject:mainView];
    
    //testButtonPressed IBAction should be triggered
    [[mock expect] testButtonPressed:[OCMArg any]];
    
    //simulate button press 
    [mainView.testButton sendActionsForControlEvents: UIControlEventTouchUpInside];
    
    [mock verify];
    

    If IBAction is not connected, the test will fail with error "expected method was not invoked".