Is it possible to test IBAction?

sash picture sash · Sep 9, 2013 · Viewed 7.3k times · Source

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?

Answer

Jon Reid picture Jon Reid · Sep 11, 2013

For full unit testing, each outlet/action needs three tests:

  1. Is the outlet hooked up to a view?
  2. Is the outlet connected to the action we want?
  3. Invoke the action directly, as if it had been triggered by the outlet.

I do this all the time to TDD my view controllers. You can see an example in this screencast.

It sounds like you're asking specifically about the second step. Here's an example of a unit test verifying that a touch up inside myButton will invoke the action doSomething: Here's how I express it using OCHamcrest. (sut is a test fixture for the system under test.)

- (void)testMyButtonAction {
    assertThat([sut.myButton actionsForTarget:sut
                              forControlEvent:UIControlEventTouchUpInside],
               contains(@"doSomething:", nil));
}

Alternatively, here's a version without Hamcrest:

- (void)testMyButtonAction {
    NSArray *actions = [sut.myButton actionsForTarget:sut
                              forControlEvent:UIControlEventTouchUpInside];
    XCTAssertTrue([actions containsObject:@"doSomething:"]);
}