xctest – 如何testing一个新的视图加载button按下
刚开始xcode 5和xctest。 如何testing一个视图加载button按下。 我已经编程添加的方法,当rightBarButtonItem被点击时被调用
action:@selector(onSettingsButton)
并在onSettingsButton
-(void) onSettingsButton{ SettingsViewController *svc = [[SettingsViewController alloc] init]; [self.navigationController pushViewController:svc animated:YES]; }
如何编写xctest以确保SettingsViewController调出设置视图? 谢谢。
您需要一个交互testing – 也就是检查对象之间交互的testing。 在这种情况下,您需要使用SettingsViewController
在导航控制器上调用-pushViewController:animated:
所以我们想把一个模拟对象放到self.navigationController
,我们可以问:“你按预期调用了吗?
我将假设该类的一个简单名称:MyView。
我会这样做的方式是Subclass和覆盖navigationController
。 所以在我的testing代码中,我会做这样的事情:
@interface TestableMyView : MyView @property (nonatomic, strong) id mockNavigationController; @end @implementation TestableMyView - (UINavigationController *)navigationController { return mockNavigationController; } @end
现在,而不是创build一个MyView,testing将创build一个TestableMyView并设置其mockNavigationController
属性。
这个模拟可以是任何东西,只要它响应-pushViewController:animated:
并logging参数。 这是一个简单的例子,手工:
@interface MockNavigationController : NSObject @property (nonatomic) int pushViewControllerCount; @property (nonatomic, strong) UIViewController *pushedViewController; @property (nonatomic) BOOL wasPushViewControllerAnimated; @end @implementation MockNavigationController - (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated { self.pushViewControllerCount += 1; self.pushedViewController = viewController; self.wasPushViewControllerAnimated = animated; } @end
最后,这是一个testing:
- (void)testOnSettingsButton_ShouldPushSettingsViewController { // given MockNavigationController *mockNav = [[MockNavigationController alloc] init]; TestableMyView *sut = [[TestableMyView alloc] init]; sut.mockNavigationController = mockNav; // when [sut onSettingsButton]; // then XCTAssertEquals(1, mockNav.pushViewControllerCount); XCTAssertTrue([mockNav.pushedViewController isKindOfClass:[SettingsViewController class]]); }
这些东西可以通过使用模拟对象框架,如OCMock,OCMockito,或猕猴桃的嘲笑简化。 但是我认为首先应该先手动,这样才能理解这些概念。 然后select有帮助的工具。 而且如果你知道如何手工完成,你永远不会说:“嘲笑框架X没有做我所需要的!我被困住了!
find一个方法。 也许有其他人..
- (void)testSettingsViewShowsWhenSettingsButtonIsClicked{ [self.tipViewController onSettingsButton]; id temp = self.tipViewController.navigationController.visibleViewController; XCTAssertEqual([temp class], [SettingsViewController class], @"Current controller should be Settings view controller"); }
首先调用onSettingsButton,与点击button相同,但不是真的。 也许这个简单的testing案例可以吗? 如何模拟实际的新闻?
然后从应用程序的rootview的tipviewcontoller获取当前视图,并检查它是一个SettingsViewController。