Is it possible to test IBAction?

后端 未结 7 779
深忆病人
深忆病人 2021-01-05 13:50

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 bet

7条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-05 14:13

    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:"]);
    }
    

提交回复
热议问题