iPhone Nib如何使用逻辑测试进行单元测试?

时间:2010-07-08 15:51:50

标签: objective-c iphone unit-testing octest

单元测试View Controllers似乎是iPhone开发中非常重要的一部分(see this Article)。但是,这需要从Nib初始化控制器,我发现在逻辑测试中无法正确执行。

在逻辑测试中从Bundle (see this Question)加载资源可以正常工作。甚至可以加载Nibs:

    UntitledViewController* controller = [[UntitledViewController alloc]initWithNibName:nil bundle:[NSBundle bundleForClass:[self class]]];

。但是,只有nib只包含 UIViews ,它才有效。其他视图(我试过UITableView和UISwitch)导致otest失败,代码为138.

是否可以使用逻辑测试来测试我的Nib,如果是,如何测试?

2 个答案:

答案 0 :(得分:2)

这取决于您要测试的内容。如果要验证绑定是否已正确设置,请阅读Chris Hanson's article on unit testing your Cocoa interface。我个人认为这是过度的,并导致测试代码的扩散不是很有用。但那只是我的2美分。

如果您真的尝试与测试中的那些界面元素进行交互,那么您将会发现很多otest错误,尤其是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];
  }

答案 1 :(得分:0)

改为使用应用程序测试,并在设备上驱动/检查您的UI。