这取决于您要测试的内容。如果您想验证您的绑定设置是否正确,请阅读Chris Hanson 关于单元测试 Cocoa 接口的文章。我个人认为这是矫枉过正,并导致测试代码的扩散不是很有用。但这只是我的 2 美分。
如果您实际上尝试在测试中与这些界面元素进行交互,您最终会遇到许多实际错误,正如您所发现的,尤其是 UIActionSheets 和 UITableViews。
但是你的目标应该是单元测试你的控制器的行为,而不是苹果的 UI 对象的行为。我发现最好的方法是使用OCMock来模拟 UI 元素并验证控制器是否对它们进行了预期的调用。这里有几个例子:
-(void)testClickingAButtonHidesAView {
//setup
id mockViewToHide = [OCMockObject mockForClass:[UIView class]];
[[mockViewToHide expect] setHidden:YES];
[controller setSomeView:mockViewToHide];
// hideButtonClicked is an IBAction that is the hide button's target
[controller hideButtonClicked];
[mockViewToHide verify];
}
-(void)testActionSheetPublishClick {
// ModelManager is the controller's dependency, which publishes Items
id mockModelManager = [OCMockObject mockForClass:[ModelManager class]];
[controller setModelManager:mockModelManager];
// this doesn't really need to be mocked, but it's a convenient way to create
// a reference you can validate in expect:
id mockItem = [OCMockObject mockForClass:[Item class]];
[controller setCurrentItem:mockItem];
// when the user clicks "Publish" (the first button on the action sheet),
// the controller should publish the current item
[[mockModelManager expect] publishItem:mockItem];
// stub object so I know which action sheet was clicked
id mockPublishActionSheet = [OCMockObject mockForClass:[UIActionSheet class]];
[controller setPublishConfirmation:mockPublishActionSheet];
// simulate action sheet click
[controller actionSheet:mockPublishActionSheet didDismissWithButtonIndex:0];
[mockModelManager verify];
}